Set Sorting Order Column in Stored Procedure Parameter
November 20th, 2006 by Ivan Uzunov
Changing the sorting order by passing a parameter to a stored procedure it’s a little bit tricky. The following example will return all the users form table Users (id, first_name, last_name, published_feedbacks_count, positive_feedback_percentage) in the order set by parameters @sort_column and @sort_desc. The parameter @sort_column is used to pass the column to be sorted. The parameter @sort_desc is user to set the sorting direction ascending (0) or descending (1). To set the sorting order I’m using the CASE statement. Unfortunately I’ve hit a wall trying to set the sorting order for columns with different type (ex. nvarchar and int). That is why I’ve grouped the sorting SQL statements by the data type of the sorting column.
MS SQL Server, Sorting in Stored Procedure, T SQLCREATE PROCEDURE [dbo].[stpGetUsers]
@sort_column varchar(50),
@sort_desc bit
AS
BEGIN
SET NOCOUNT ON;
IF @sort_column=’first_name’ OR @sort_column=’last_name’ BEGIN
– SORT BY TEXT (nvarchar) COLUMNS
SELECT *
FROM Users
ORDER BY
CASE @sort_desc
WHEN 1 THEN – DESCENDING ORDER
CASE @sort_column
WHEN ‘first_name’ THEN first_name
WHEN ‘last_name’ THEN last_name
ELSE first_name
END
END
DESC,
CASE @sort_desc
WHEN 0 THEN – ASCENDING ORDER
CASE @sort_column
WHEN ‘first_name’ THEN first_name
WHEN ‘last_name’ THEN last_name
ELSE first_name
END
END
END ELSE BEGIN
– SORT BY NUMBER (int) COLUMNS
SELECT *
FROM Users
ORDER BY
CASE @sort_desc
WHEN 1 THEN – DESCENDING ORDER
CASE @sort_column
WHEN ‘published_feedbacks_count’ THEN published_feedbacks_count
WHEN ‘positive_feedback_percentage’ THEN positive_feedback_percentage
ELSE published_feedbacks_count
END
END
DESC,
CASE @sort_desc – ASCENDING ORDER
WHEN 0 THEN
CASE @sort_column
WHEN ‘published_feedbacks_count’ THEN published_feedbacks_count
WHEN ‘positive_feedback_percentage’ THEN positive_feedback_percentage
ELSE published_feedbacks_count
END
END
END
END



