I've the following MS SQL stored procedure. I need to sort the results without using dynamic SQL and sp_executesql
method
@Order by can have the possible values ProductName ASC
, ProductName DESC
, ProductCode ASC
, VendorName DESC
, VendorCode
or ClientName
I was trying to use ORDER BY CASE
, is there any issue if the ProductName
, ProductCode
are of different type?
ALTER PROCEDURE [dbo].[SortedReport]
(
@ClientID INT,
@RecordLimit,
@FromDate DATETIME,
@ToDate DATETIME,
@OrderBy NVARCHAR(MAX)
)
AS
BEGIN
IF (@OrderBy IS NULL) BEGIN
SET @OrderBy = 'ProductName';
END
SELECT TOP (@RecordLimit)
sv.ClientID,
sv.VendorID,
sv.ProductID,
sv.TransactionTime,
sv.ClientName,
sv.VendorName,
sv.ProductName,
sv.ProductCode,
sv.VendorCode,
FROM SortedReportiew AS sv
WHERE (sv.ClientID = @ClientID)
AND (sv.TransactionTime >= @FromDate)
AND (sv.TransactionTime < @Date)
Update:
Is the below part correct? ref from here
ORDER BY
CASE @OrderBy WHEN 'ProductCode ASC' THEN ProductCode WHEN 'ProductCode DESC' THEN ProductCode END DESC,
CASE @OrderBy WHEN 'ProductName ASC' THEN ProductName WHEN 'ProductName DESC' THEN ProductName END DESC,