Wednesday, November 23, 2011

Dynamic order by in SQL select query for sorting fields


declare @fieldname nvarchar(max);
declare @sortdirection int;
--you can set any field here for ex:- Id as field name
set @fieldname = 'Id'
--you can set sort direction here for ex:- 0 for desc
set @sortdirection = 0


select * from TblEmployee
   ORDER BY    
CASE WHEN @fieldname = 'Id' and @sortdirection = 0 THEN Id END DESC,
CASE WHEN @fieldname = 'Id' and @sortdirection = 1 THEN Id END ASC,
CASE WHEN @fieldname = 'Name' and @sortdirection = 0 THEN Name END DESC,
CASE WHEN @fieldname = 'Name' and @sortdirection = 1 THEN Name END ASC

No comments:

Post a Comment