Click here to Skip to main content
11,799,282 members (74,829 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: SQL-server-2005 SQL-Server , +
Hey Guys,

i have a stored procedure which selects from the data base,

i want to add order by column as a parameter

and i want to add the sort type as a parameter too

EX: select * from Students order by @Column_Name @Sort_Type

@Column_Name is the sortable column
@Sort_Type is ASC or DESC

Any Ideas
Posted 9-Apr-13 4:39am
Edited 9-Apr-13 4:40am
govardhan4u at 9-Apr-13 10:45am
check this URL
AmrDeif at 9-Apr-13 10:48am
Is there is another way except the dynamic sql statment?
It is really necessary order data in sql statement? Can you order it in a frontend application?
govardhan4u at 9-Apr-13 10:58am
If you are calling it from a .Net code then you can generate the sql statement and call its execute comman

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Try this:
     @Column_Name VARCHAR(30),
     @Sort_Type VARCHAR(10)
    DECLARE @sql VARCHAR(2000)
    SET @sql = 'SELECT * ' +
               'FROM Students ' + 
               'ORDER BY ' + @Column_Name + ' ' + @Sort_Type
    EXEC (@sql)

As govardhan4u[^] wrote, see this article: Building Dynamic SQL In a Stored Procedure[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 463
1 CPallini 450
2 Richard MacCutchan 321
3 Maciej Los 255
4 phil.o 244
0 OriginalGriff 2,475
1 Maciej Los 1,860
2 KrunalRohit 1,496
3 CPallini 1,465
4 Richard MacCutchan 1,149

Advertise | Privacy | Mobile
Web02 | 2.8.151002.1 | Last Updated 9 Apr 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100