Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stored Procedure - Declare variable to reference a column

Status
Not open for further replies.

SkyMasterBRA

Programmer
Nov 21, 2002
12
BR
How can I do to declare a variable to reference a column in a stored procedure to use as a ORDER BY parameter?

Cya!
 
order by
case @c
when 'C1' then c1
when 'C2' then c2
when 'C3' then c3 end

if c1,c2 and c3 are of non-comparable types, you need to add apropriate casts.

You can also use dynamic sql

declare @s varchar(200)

@s = 'select ...' + ' order by ' +
case @c
when 'C1' then 'C1'
when 'C2' then 'C2'
when 'C3' then 'C3' end

exec(@s)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top