|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
T-SQL Help with Order by
In a stored procedure MS-SQL I am trying to write an order by expression that is a function of the incoming paramters.
SO for example CREATE PROCEDURE test @sortby varchar(10) AS SELECT * FROM table WHERE condition ORDER BY @SORTBY Gives an error (1008) but the error message implies that you can use a variable in the order by expression. I have tried every combination I can think of with the variable as varchar = column name, as integer . I have also tried variations of Order by COL_Name(OBJECT_ID('item"), variable) and I ether get errors or no errors but no order either. Any leads appreciated. TIA Mike |
|
#2
|
||||
|
||||
|
you need to use the EXECUTE command for a dynamic query
|
|
#3
|
|||
|
|||
|
Quote:
Got it, thanks |
|
#4
|
|||
|
|||
|
Quote:
This problem can be solved by executing the Query Dynamically Rewrite the Stored procedure as follows CREATE PROCEDURE test @sortby varchar(10) AS Declare @QString nvarchar(500) /* The @SORTBY Must be a valid Column Name*/ Set @QString = 'SELECT * FROM table WHERE condition Order by ' + @SORTBY /*sp_ExecuteSql - This is a Sql Server Built in Stored Procedure. this is used to execute a query string as a query */ exec sp_ExecuteSql @QString --- Hope this solves your problem Happy Programming |
![]() |
| Viewing: Dev Shed Forums > Databases > MS SQL Development > T-SQL Help with Order by |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|