Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Bizzarre Sorting

Author  Topic 

souLTower
Starting Member

39 Posts

Posted - 2009-03-12 : 06:09:42
Check this out please


-- Wacky Sort Order Test
-- Create a table of data
create table #fiscal(fldYear int, fldStage int)

-- Populate the data
declare @c int
set @c = 0

while @c < 400
begin
insert into #fiscal(fldYear, fldStage)
select 2005, case when @c > 200 then 4 else 2 end
set @c = @c + 1
end


-- Queries
-- Note that the calculated field is named the same
-- as the table field
select cast(P.fldYear as varchar) + case when P.fldStage > 2 then ' Final' else ' Initial' end as fldYear
FROM #fiscal P order by P.fldYear, P.fldStage


-- Note the calculated field is named differently
-- than the table field
select cast(P.fldYear as varchar) + case when P.fldStage > 2 then ' Final' else ' Initial' end as fldFoo
FROM #fiscal P order by P.fldYear, P.fldStage


-- Note that the table field is included in the
-- query under an aliased name
select P.fldYear as JIMMY, cast(P.fldYear as varchar) + case when P.fldStage > 2 then ' Final' else ' Initial' end as fldYear
FROM #fiscal P order by P.fldYear, P.fldStage



Check out the execution plans for the queries. Note that in the first query, even though you state that you want to order on the table field, the execution plan orders on the calculated field. In the later queries, by changing the name of the calculated field or including the table field in the query the execution plan orders correctly.

Interesting huh?
ST

God Bless
   

- Advertisement -