SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Sorting Problem
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

bandi
Flowing Fount of Yak Knowledge

India
2202 Posts

Posted - 03/13/2013 :  09:24:36  Show Profile  Reply with Quote
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

India
52309 Posts

Posted - 03/13/2013 :  10:08:44  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

4612 Posts

Posted - 03/13/2013 :  12:15:05  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

India
2202 Posts

Posted - 03/14/2013 :  00:09:22  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000