Click here to Skip to main content
Rate this: bad
good
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
AmrDeif651
Edited 9-Apr-13 5:40am
v2
Comments
govardhan4u at 9-Apr-13 10:45am
   
check this URL
 
http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure
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
good
Please Sign up or sign in to vote.

Solution 1

Try this:
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[^]
  Permalink  

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

  Print Answers RSS
0 BillWoodruff 300
1 Mathew Soji 274
2 Afzaal Ahmad Zeeshan 268
3 DamithSL 225
4 Sergey Alexandrovich Kryukov 205
0 OriginalGriff 6,249
1 Sergey Alexandrovich Kryukov 5,853
2 DamithSL 5,183
3 Manas Bhardwaj 4,673
4 Maciej Los 3,865


Advertise | Privacy | Mobile
Web04 | 2.8.1411019.1 | Last Updated 9 Apr 2013
Copyright © CodeProject, 1999-2014
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