In this Article, We will explain how do you Order By parameter in SQL Server .
Lets Suppose , We have Test database “TestDb” and table “UserT”.
SELECT UserId, UserName FROM UserT
UserT Table:
UserId UserName
1 Test 4
2 Test 1
3 Test 2
4 Test 3
Now we want to sort the table in ascending or descending order but the sorting can be taken care of with CASE Expression.
Here is the example to sort the table using ORDER BY @parameter.
/****** Script for SelectTopNRows command from SSMS ******/
DECLARE @OrderByDirection int;
DECLARE @SortingBy VARCHAR(100);
SET @OrderByDirection = 5;
SET @SortingBy = 'Username';
SELECT UserId, UserName
FROM UserT
ORDER BY
CASE WHEN @OrderByDirection = 1 THEN
CASE
WHEN @SortingBy = 'Username' THEN Username
END
END ASC
, CASE WHEN @OrderByDirection = 5 THEN
CASE
WHEN @SortingBy = 'Username' THEN Username
END
END DESC;
In above Query, You can see that we declared two variables @OrderByDirection and @SortingBy.
@OrderByDirection used in descending Order and value is assigned as ‘5’ and Value assigned as ‘UserName’ for Variable @SortingBy which is used for column “UserName” . You can easily sort the table using Order by Parameter by using this scenario.
Result :
UserId UserName
1 Test 4
4 Test 3
3 Test 2
2 Test 1
If you want to sell your readymade software to the genuine clients or businessman, list your software with details and demo links.
Clients will find it using our advanced search filter and will contact you directly.
No any charge for the product lsiting.