Click here to Skip to main content
13,091,300 members (52,586 online)
Rate this:
Please Sign up or sign in to vote.
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
Updated 9-Apr-13 4: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 |
Web03 | 2.8.170813.1 | Last Updated 9 Apr 2013
Copyright © CodeProject, 1999-2017
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