Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Updated 9-Apr-13 4:40am
v2
Comments
govardhan4u 9-Apr-13 10:45am    
check this URL

http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure
_ProgProg_ 9-Apr-13 10:48am    
Is there is another way except the dynamic sql statment?
José Amílcar Casimiro 9-Apr-13 10:52am    
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

Try this:
SQL
CREATE PROCEDURE MyProc
     @Column_Name VARCHAR(30),
     @Sort_Type VARCHAR(10)
AS
BEGIN
    DECLARE @sql VARCHAR(2000)

    SET @sql = 'SELECT * ' +
               'FROM Students ' + 
               'ORDER BY ' + @Column_Name + ' ' + @Sort_Type
    EXEC (@sql)

END


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

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900