In this article , let us see an example for ORDER BY with CASE statement
Consider below sample data :
If we are required to sort based on column and if the name of the column is passed as input , then we can make use of ORDER BY with CASE statement
Consider below sample data :
DECLARE @Tmp TABLE (Id VARCHAR(5),Name VARCHAR(5)) INSERT @Tmp SELECT 1,'C' INSERT @Tmp SELECT 2,'B' INSERT @Tmp SELECT 3,'A'
If we are required to sort based on column and if the name of the column is passed as input , then we can make use of ORDER BY with CASE statement
--Sort Input DECLARE @Sortby VARCHAR(20) = 'Name' SELECT * FROM @Tmp ORDER BY CASE WHEN @Sortby = 'Name' THEN Name ELSE Id END --Sort Input SET @Sortby = 'Id' SELECT * FROM @Tmp ORDER BY CASE WHEN @Sortby = 'Name' THEN Name ELSE Id END
Reference links :
- http://technet.microsoft.com/en-us/library/ms188385.aspx
- http://technet.microsoft.com/en-us/library/ms188723%28v=sql.105%29.aspx
No comments:
Post a Comment