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
 General SQL Server Forums
 New to SQL Server Programming
 Sorting Problem

Author  Topic 

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-03-13 : 09:24:36
Hi,

I have one stored procedure...
I have to sort result set by input parameter @SortColumn

CREATE PROC testProc( @SortColumn VARCHAR(60)) -- ColumnName + ASC/DESC
AS
BEGIN
SELECT * FROM TableName ORDER BY @sortColumn -- Is it possible without dynamic query
END

--
Chandu

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-03-13 : 10:08:44
nope you cant pass the columnname and sort order unless you use dynamical sql. columnname alone you can pass but direction has to static.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-03-13 : 12:15:05
Kinda sorta.. You can make use of CASE expressions to do a "dynamic" sort. But, not quite to the level of just sorting on the variable itself. For example:
ORDER BY
CASE
WHEN @SortColumn = 'CustomerName' AND @SortDir = 'ASC'
THEN CustomerName
END ASC,
CASE
WHEN @SortColumn = 'CustomerName' AND @SortDir = 'DESC'
THEN CustomerName
END DESC,
...
Go to Top of Page

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-03-14 : 00:09:22
yes.. i have already done like Lamprey's method... but the problem is i have column names of types varchar(250), datetime2, bigint. Thats why casted all columns to VARCHAR(250)...

The sorting order for Bigint will vary... right? What is the fix for this problem?


--
Chandu
Go to Top of Page
   

- Advertisement -