I’m using a stored procedure to try to get the first few rows from a sorted SQL query where the input paramaters specifiy the amount of rows to retrieve and the sorting criteria.
I’ve been able to properly retrieve the first few rows however when I try to sort the results, they simply appear sorted using the default criteria (Primary key).
So I was wondering if anyone could take a look at it?
USE [database]
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[x0]
@username nvarchar(50),
@sortBy varchar(50),
@sortDirection varchar(4),
@startRow int,
@endRow int
AS
With Ordering AS(
SELECT ROW_NUMBER() OVER (Order by
CASE WHEN @sortBy='datecreate' THEN 'datecreate'
WHEN @sortBy='id' THEN 'id'
WHEN @sortBy='DisplayName' THEN 'DisplayName'
END,
CASE WHEN @sortDirection='asc' THEN 'asc'
WHEN @sortDirection='desc' THEN 'desc'
END) AS RowNumber,
dbo.x1.*, dbo.x2.*
FROM dbo.x1 INNER JOIN dbo.x2 ON dbo.x1.type = dbo.x2.type
where username = @username
)
SELECT RowNumber, *, DisplayName AS DisplayName
FROM Ordering
Where RowNumber BETWEEN @startRow AND @endRow
I’ve also tried moving the sorting criteria to the outer SQL query (Where RowNumber BETWEEN @startRow AND @endRow) without much luck.
You could do it this way:
But quite honestly I think you’ll get better performance from dynamic SQL (and if the
optimize for ad hoc workloadssetting is enabled, it won’t suffer from the parameter sniffing issues inherent in the above solution, or plan cache bloat):