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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using dynamic variables in the ORDER BY clause

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I want to be able to give one of my applications the ability to have query results sorted based on user input. To do this of course required variables. I can get a dynamic SQL query to work but like below... but having hardcode / 'set' the value makes the whole thing useless.

declare @OrderBy_1 [varchar](20)
declare @sql varchar(1000)

select @OrderBy_1 = 'PSID'
set @sql = "select * from tblPS WHERE PSID = '100' Order By " + @OrderBy_1

exec (@sql)

How can I make @OrderBy_1 dynamically fed by a form input?

Cclabaugh
 
Pass the criteria to a stored procedure.

Create Procedure usp_Sample @OrderBy_1 varchar(20) As

declare @sql varchar(1000)

Set @sql = "select * from tblPS WHERE PSID = '100' Order By " + @OrderBy_1

exec (@sql)
Go

From your client application you would execute the stored procedure as "Exec usp_Sample 'PSID'" and the SP would accept 'PSID' as the parameter, build the SQL string, execute it and return the record set to the client in the proper order. Terry

Neither success nor failure is ever final. -Roger Babson
 
Thank you. Your suggestion worked, except that I didn't use 'GO'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top