Click here to Skip to main content
11,930,679 members (60,130 online)
Rate this:
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 5:39am
Edited 9-Apr-13 5:40am
govardhan4u 9-Apr-13 10:45am
check this URL
AmrDeif 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 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
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web04 | 2.8.151126.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