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)
 Dynamic ORDER BY with different Data Types

Author  Topic 

Page47
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2002-09-12 : 08:52:30
Consider this sample table...

create table #orderbytest (a char(1), b int)

insert #orderbytest
select
char((n%26) + 97),
floor(rand(cast(newid() as varbinary(4))) * 1000000)
from
numbers -- (FYI - create table numbers (n int) and fill with 1 thru 10000)
go

 
I am trying to do a Dynamic ORDER BY clause like this ...


declare @orderby char(1)
set @orderby = 'b'

select
a,
b
from
#orderbytest
order by
case
when @orderby = 'a' then a
when @orderby = 'b' then b
end ASC

 
Now when I set @orderby = 'b' it works, but if I set @orderby = 'a' I get ...
quote:
Server: Msg 245, Level 16, State 1, Line 4
Syntax error converting the varchar value 'a' to a column of data type int.

Does anyone have a good workaround for this? Rob?

Jay White
{0}

nr
SQLTeam MVY

12543 Posts

Posted - 2002-09-12 : 09:05:06
order by
case when @orderby = 'a' then a end asc
case when @orderby = 'b' then b end asc


you can put an else null in the case statements for clarity if you wish.

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

Page47
Master Smack Fu Yak Hacker

2878 Posts

Posted - 2002-09-12 : 09:12:29
Thanks!

Jay White
{0}
Go to Top of Page
   

- Advertisement -