SQL Server Paging, with dynamic ordering? - sql

I found this nice example of doing paging in SQL Server, however, I need to do some dynamic ordering. That is, the user passes in an integer, which then gets used to do the ordering, like this:
ORDER BY
CASE WHEN #orderBy = 1 THEN DateDiff(ss, getdate(), received_date) --oldest
WHEN #orderBy = 2 THEN DateDiff(ss, received_date, getdate()) --newest
WHEN #orderBy = 3 THEN message_id --messageid
WHEN #orderBy = 4 THEN LEFT(person_reference, LEN(person_reference)-1) --personid
END
Is it possible to do paging, with this form of dynamic ordering?

What you do instead is move the ORDER BY code into the ROW_NUMBER window function.
Like this example
SELECT * -- your columns
FROM
(
SELECT *, ROWNUM = ROW_NUMBER() OVER (
ORDER BY
CASE WHEN #orderBy = 1 THEN DateDiff(ss, getdate(), received_date) --oldest
WHEN #orderBy = 2 THEN DateDiff(ss, received_date, getdate()) --newest
WHEN #orderBy = 3 THEN message_id --messageid
WHEN #orderBy = 4 THEN LEFT(person_reference, LEN(person_reference)-1) --personid
END
)
FROM TBL
) R
where ROWNUM between ((#pageNumber-1)*#PageSize +1) and (#pageNumber*#PageSize)
The main problem with the complex ORDER BY and the windowing function is that you end up fully materializing the rownum against all rows before returning just one page.

Related

Order by Case When ColumnName as Variable

I've seen plenty of examples where people are using CASE WHEN in the ORDER BY clause of a Select statement. Typically, they're comparing the value of a variable to a string of the column name.
This is fine but what about when you have an extremely wide table?
Can you not just say something like
ORDER BY
CASE WHEN #SortDesc = 1 THEN #SortField END DESC,
CASE WHEN #SortDesc = 0 THEN #SortField END ASC
Or do you really really have to have a CASE WHEN for every column in the result set? Edit: Note that this is being converted from a SQL string to plain old SQL so dynamically building and executing it as a string isn't an option.
You can build up a dynamic sql string for something like this:
DECLARE #SortDesc varchar(max)
SELECT #SortDesc = [query to get your Sort column name].
DECLARE #sql varchar(max) = 'SELECT * FROM TABLE ORDER BY ' + #SortDesc
exec(#sql)
Or do you really really have to have a CASE WHEN for every column in
the result set?
ORDER BY
CASE WHEN #SortDesc = 1 THEN #SortField END DESC,
CASE WHEN #SortDesc = 0 THEN #SortField END ASC
The point is that your shown code won't order. #SortField is replaced on all records by the same value, and you have no special order at all.
What you can do is address a #orderBy variable witch controls what realy ocurrs like this:
ORDER BY
CASE WHEN #orderBy = 'NameDesc' THEN name END DESC,
CASE WHEN #orderBy = 'NameAsc' THEN name END,
CASE WHEN #orderBy = 'someDateDesc' THEN someDate END DESC,
CASE WHEN #orderBy = 'someDateAsc' THEN someDate END,
CASE WHEN #orderBy = 'IdDesc' THEN Id END DESC,
CASE WHEN #orderBy = 'IdAsc' THEN Id END
Here you are ordering by six criterias, but five of them are null for all records, so your efecive order is by the selected field. And yes, you will need to write all variants that you want to use.

Custom sorting and pagination over large tables

I'm used to get benefits from ROW_NUMBER function in MS SQL Server scripts since 2005 version. But I noticed there is big performance disadvantage querying big tables using this function.
Imagine table with four columns (a real table from external database has more columns, but I used only those to avoid complexity of example):
DECLARE TABLE StockItems (
Id int PRIMARY KEY IDENTITY(1,1),
StockNumber nvarchar(max),
Name nvarchar(max),
[Description] nvarchar(max))
I've written procedure for querying this table filled up by 200 000+ rows with following parameters:
#SortExpression - name of column by which I want to sort
#SortDirection - bit information (0=ascending, 1=descending)
#startRowIndex - zero based index at which I want retrieve rows
#maximumRows - number of rows to be retrieved
Query:
SELECT sortedItems.Id
,si.StockNumber
,si.Name
,si.Description
FROM (SELECT s.Id
,CASE WHEN #SortDirection=1 THEN
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN
ROW_NUMBER() OVER (ORDER by s.Name DESC)
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN
ROW_NUMBER() OVER (ORDER by s.StockNumber DESC)
ELSE ROW_NUMBER() OVER (ORDER by s.StockNumber DESC)
END
ELSE
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN
ROW_NUMBER() OVER (ORDER by s.Name ASC)
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN
ROW_NUMBER() OVER (ORDER by s.StockNumber ASC)
ELSE ROW_NUMBER() OVER (ORDER by s.StockNumber ASC)
END
END AS RowNo
FROM stockItems s
) as sortedItems
INNER JOIN StockItems si ON sortedItems.Id=si.Id
ORDER BY sortedItems.RowNo
In situation when number of rows is growing rapidly, ROW_NUMBER became ineffective, because must sort all rows.
Please can you help me to avoid this performance disadvantage and speed up the query?
Check the execution path. ROW_NUMBER() does not have big impact as long as you have the correct index. The problem with your query isn't in the ROW_NUMBER().
Use dynamic instead, it will eliminate the 2 SEGMENTATION caused by the ROW_NUMBER().
I tested this on a >4mil records table and it returns in split second:
DECLARE #SortExpression VARCHAR(32) SET #SortExpression = 'StockNumber'
DECLARE #SortDirection BIT SET #SortDirection = 1
DECLARE #startRowIndex BIGINT SET #startRowIndex = 1000
DECLARE #maximumRows BIGINT SET #maximumRows = 5000
DECLARE #vsSQL AS NVARCHAR(MAX)
SET #vsSQL = ''
SET #vsSQL = #vsSQL + 'SELECT sortedItems.Id, sortedItems.StockNumber, sortedItems.Name, sortedItems.Description FROM ( '
SET #vsSQL = #vsSQL + 'SELECT s.Id, s.StockNumber, s.Name, s.Description, '
SET #vsSQL = #vsSQL + 'ROW_NUMBER() OVER (ORDER BY ' + #SortExpression + ' ' + CASE #SortDirection WHEN 1 THEN 'DESC' ELSE 'ASC' END + ') AS RowNo '
SET #vsSQL = #vsSQL + 'FROM StockItems s '
SET #vsSQL = #vsSQL + ') AS sortedItems '
SET #vsSQL = #vsSQL + 'WHERE RowNo BETWEEN ' + CONVERT(VARCHAR,#startRowIndex) + ' AND ' + CONVERT(VARCHAR,#startRowIndex+#maximumRows) + ' '
SET #vsSQL = #vsSQL + 'ORDER BY sortedItems.RowNo'
PRINT #vsSQL
EXEC sp_executesql #vsSQL
You can move the case expression to an order by clause:
order by (case when #SortDirection=1 and CHARINDEX('Name',#SortExpression)=1 then s.name end) desc,
(case when #SortDirection=1 and CHARINDEX('StockNumber',#SortExpression)=1 then s.StockNumber end) desc,
(case when #SortDirection=1 and (CHARINDEX('StockNumber',#SortExpression)<>1 and CHARINDEX('Name',#SortExpression)<>1) then va.match end) desc,
(case when #SortDirection<>1 and CHARINDEX('Name',#SortExpression)=1 then s.name end) asc,
(case when #SortDirection<>1 and CHARINDEX('StockNumber',#SortExpression)=1 then s.StockNmber end) asc,
(case when #SortDirection<>1 and (CHARINDEX('StockNumber',#SortExpression)<>1 and CHARINDEX('Name',#SortExpression)<>1) then va.match end) asc
I notice the expression has va.match, so it doesn't really match any tables in your query. So, I'm just putting in the order by expression.
And, yes, as the table gets bigger, this is going to take more time. I don't know that the order by will be more efficient than the row_number(), but it is possible.
If you need to order the rows, then you have to do a sort, one way or another (perhaps you could use an index instead). If you don't care about the order, you could take your chances with:
row_number() over (order by (select NULL))
In SQL Server, I have found that this assigns a sequential number without a separate sort. However, this is not guaranteed (I haven't found any documentation to support this use). And, the result is not necessarily stable from one run to the next.
I've found solution how to avoid performance penalty using ROW_NUMBER() function over large result sets. A goal I didn't write in my question was to avoid declaring query as nvarchar variable and executing it, because it can cause open door for SQL injection.
So, solution is to query data as much as possible in required sort order, then query result set and switch ordering and get data only for current page. Finally I can take result ordered in opposite order and order them again.
I defined new variable #innerCount to query most inner result set and order it as query client specify in #sortExpression and #sortDirection variables
SET #innerCount = #startRowIndex + #maximumRows
Select OppositeQuery.Id
,s.StockNumber
,s.Name
,s.Description
FROM (SELECT TOP (#maximumRows) InnerItems.Id
FROM
(SELECT TOP (#innerCount) sti.Id
FROM stockItems sti
ORDER BY
CASE WHEN #SortDirection=1 THEN
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN sti.Name
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN sti.StockNumber
ELSE sti.StockNumber
END
END DESC
CASE WHEN ISNULL(#SortDirection,0)=0 THEN
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN sti.Name
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN sti.StockNumber
ELSE sti.StockNumber
END
END ASC
) as InnerQuery
INNER JOIN StockItems si on InnerQuery.Id=si.Id
ORDER BY
CASE WHEN #SortDirection=1 then
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN si.Name
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN si.StockNumber
ELSE si.StockNumber
END
END ASC
CASE WHEN ISNULL(#SortDirection,0)=0 then
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN si.Name
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN si.StockNumber
ELSE si.StockNumber
END
END ASC
) AS OppositeQuery
INNER JOIN StockItems s on OppositeQuery.Id=s.Id
ORDER BY
CASE WHEN #SortDirection=1 THEN
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN s.Name
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN s.StockNumber
ELSE s.StockNumber
END
END DESC
CASE WHEN ISNULL(#SortDirection,0)=0 THEN
CASE
WHEN CHARINDEX('Name',#SortExpression)=1 THEN s.Name
WHEN CHARINDEX('StockNumber',#SortExpression)=1 THEN s.StockNumber
ELSE s.StockNumber
END
END ASC
Disadvantage of this approach is that I have to sort data three times, but in case of multiple inner joins to StockItems table subqueries are much faster than using ROW_NUMBER() function.
Thank to all contributors for help.

SQL stored procedure passing parameter into "order by"

Using Microsoft SQL server manager 2008.
Making a stored procedure that will "eventually" select the top 10 on the Pareto list. But I also would like to run this again to find the bottom 10.
Now, instead of replicating the query all over again, I'm trying to see if there's a way to pass a parameter into the query that will change the order by from asc to desc.
Is there any way to do this that will save me from replicating code?
CREATE PROCEDURE [dbo].[TopVRM]
#orderby varchar(255)
AS
SELECT Peroid1.Pareto FROM dbo.Peroid1
GROUP by Pareto ORDER by Pareto #orderby
Only by being slightly silly:
CREATE PROCEDURE [dbo].[TopVRM]
#orderby varchar(255)
AS
SELECT Peroid1.Pareto FROM dbo.Peroid1
GROUP by Pareto
ORDER by CASE WHEN #orderby='ASC' THEN Pareto END,
CASE WHEN #orderby='DESC' THEN Pareto END DESC
You don't strictly need to put the second sort condition in a CASE expression at all(*), and if Pareto is numeric, you may decide to just do CASE WHEN #orderby='ASC' THEN 1 ELSE -1 END * Pareto
(*) The second sort condition only has an effect when the first sort condition considers two rows to be equal. This is either when both rows have the same Pareto value (so the reverse sort would also consider them equal), of because the first CASE expression is returning NULLs (so #orderby isn't 'ASC', so we want to perform the DESC sort.
You might also want to consider retrieving both result sets in one go, rather than doing two calls:
CREATE PROCEDURE [dbo].[TopVRM]
#orderby varchar(255)
AS
SELECT * FROM (
SELECT
*,
ROW_NUMBER() OVER (ORDER BY Pareto) as rn1,
ROW_NUMBER() OVER (ORDER BY Pareto DESC) as rn2
FROM (
SELECT Peroid1.Pareto
FROM dbo.Peroid1
GROUP by Pareto
) t
) t2
WHERE rn1 between 1 and 10 or rn2 between 1 and 10
ORDER BY rn1
This will give you the top 10 and the bottom 10, in order from top to bottom. But if there are less than 20 results in total, you won't get duplicates, unlike your current plan.
try:
CREATE PROCEDURE [dbo].[TopVRM]
(#orderby varchar(255)
AS
IF #orderby='asc'
SELECT Peroid1.Pareto FROM dbo.Peroid1
GROUP by Pareto ORDER by Pareto asc
ELSE
SELECT Peroid1.Pareto FROM dbo.Peroid1
GROUP by Pareto ORDER by Pareto desc
I know it's pretty old, but just wanted to share our solution here, hoping to help someone :)
After some performance tests for several candidate solutions (some of them posted in this thread), we realized you must be really careful with your implementation: your SP performance could be hugely impacted, specially when you combine it with pagination problem.
The best solution we found was to save raw results, ie. just applying filters, in a temporal table (#RawResult in the example), adding afterwards the ORDER BY and OFFSET clauses for pagination. Maybe it's not the prettiest solution (as you are force to copy & paste a clause twice for each column you want to sort), but we were unable to find other better in terms of performance.
Here it goes:
CREATE PROCEDURE [dbo].[MySP]
-- Here goes your procedure arguments to filter results
#Page INT = 1, -- Resulting page for pagination, starting in 1
#Limit INT = 100, -- Result page size
#OrderBy NVARCHAR(MAX) = NULL, -- OrderBy column
#OrderByAsc BIT = 1 -- OrderBy direction (ASC/DESC)
AS
-- Here goes your SP logic (if any)
SELECT
* -- Here goes your resulting columns
INTO
#RawResult
FROM
...
-- Here goes your query data source([FROM], [WHERE], [GROUP BY], etc)
-- NO [ORDER BY] / [TOP] / [FETCH HERE]!!!!
--From here, ORDER BY columns must be copy&pasted twice: ASC and DESC orders for each colum
IF (#OrderByAsc = 1 AND #OrderBy = 'Column1')
SELECT * FROM #RawResult ORDER BY Column1 ASC OFFSET #Limit * (#Page - 1) ROWS FETCH NEXT #Limit ROWS ONLY
ELSE
IF (#OrderByAsc = 0 AND #OrderBy = 'Column1')
SELECT * FROM #RawResult ORDER BY Column1 DESC OFFSET #Limit * (#Page - 1) ROWS FETCH NEXT #Limit ROWS ONLY
ELSE
IF (#OrderByAsc = 1 AND #OrderBy = 'Column2')
SELECT * FROM #RawResult ORDER BY Column2 ASC OFFSET #Limit * (#Page - 1) ROWS FETCH NEXT #Limit ROWS ONLY
ELSE
IF (#OrderByAsc = 0 AND #OrderBy = 'Column2')
SELECT * FROM #RawResult ORDER BY Column2 DESC OFFSET #Limit * (#Page - 1) ROWS FETCH NEXT #Limit ROWS ONLY
ELSE
...
ELSE --Default order, first column ASC
SELECT * FROM #RawResult ORDER BY 1 ASC OFFSET #Limit * (#Page - 1) ROWS FETCH NEXT #Limit ROWS ONLY
This gives you more options
CREATE PROCEDURE [dbo].[TopVRM] #orderby varchar(255) = 'Pareto asc'
DECLARE #SendIt NVARCHAR(MAX)
AS
BEGIN
SET #SendIt = 'SELECT Peroid1.Pareto FROM dbo.Peroid1
GROUP by Pareto ORDER by '+ #orderby
EXEC sp_executesql #SendIt
END
GO
EXEC dbo.TopVRM 'Pareto DESC'
GO

Dynamic order by without using dynamic sql?

I have the following stored procedure which can be sorted ascending and descending on TemplateName,CreatedOn and UploadedBy. The following SP when runs doesnot sort records.if i replace 2,3,4 by columnname, i got an error message "Conversion failed when converting the nvarchar value 'Test Template' to data type int.".Please suggest how to achieve sorting.
CREATE PROCEDURE [dbo].[usp_SEL_GetRenderingTemplate]
(
#facilityID INT,
#sortOrder VARCHAR(5),
#sortExpression VARCHAR(100),
#errorCode INT OUTPUT
)
AS
BEGIN
SET NOCOUNT ON ;
BEGIN TRY
SET #sortOrder = CASE #sortOrder
WHEN 'Ascending' THEN 'ASC'
WHEN 'Descending' THEN 'DESC'
ELSE 'ASC'
END
SELECT TemplateID,
TemplateName,
CreatedOn,
( [user].LastName + ' ' + [user].FirstName ) AS UploadedBy
FROM Templates
INNER JOIN [user] ON [user].UserID = Templates.CreatedBy
WHERE facilityid = #facilityID
ORDER BY CASE WHEN #sortExpression = 'TemplateName'
AND #sortOrder = 'ASC' THEN 2
WHEN #sortExpression = 'CreatedOn'
AND #sortOrder = 'ASC' THEN 3
WHEN #sortExpression = 'UploadedBy'
AND #sortOrder = 'ASC' THEN 4
END ASC,
CASE WHEN #sortExpression = 'TemplateName'
AND #sortOrder = 'DESC' THEN 2
WHEN #sortExpression = 'CreatedOn'
AND #sortOrder = 'DESC' THEN 3
WHEN #sortExpression = 'UploadedBy'
AND #sortOrder = 'DESC' THEN 4
END DESC
SET #errorCode = 0
END TRY
BEGIN CATCH
SET #errorCode = -1
DECLARE #errorMsg AS VARCHAR(MAX)
DECLARE #utcDate AS DATETIME
SET #errorMsg = CAST(ERROR_MESSAGE() AS VARCHAR(MAX))
SET #utcDate = CAST(GETUTCDATE() AS DATETIME)
EXEC usp_INS_LogException 'usp_SEL_GetFacilityWorkTypeList',
#errorMsg, #utcDate
END CATCH
END
The dynamic ordering has to be of the same datatype. Here is an example of something that I use to case order three different datatypes - integer, date (ascending and descending), and string. This may not work for your situation, but at least you can see some techniques for casting to a common datatype.
...
ORDER BY
Case Parent.RankTypeID
When 0 Then dbo.Documents.Rank
When 1 Then Convert(int, dbo.Documents.DateStart, 112)
When 2 Then (1 - Convert(int, dbo.Documents.DateStart, 112))
When 3 Then Cast(dbo.Documents.Title as sql_variant)
End
Note:
112 is a date format of YYYYMMDD - useful for ordering.
We perform a similar sort of dynamic ordering in one of our products.
The only real different to your code is firstly, we don't use the live join.
We create a temporary table, so we can perform paging, and then apply the order.
We also use ints for ordering, cuts down on the overhead of string comparison.
It does make your SQL a bit longer, but this approach is definitely faster for the Query Optimiser. Also, and more importantly, I don't think you can mix types in Switch blocks, for ordering, so to follow your original code, you'd have to CONVERT all your data to the same time, which defeats the object :(
So you'd have
DECLARE #temp TABLE(ID int identity(1,1), TemplateID int, TemplateName nvarchar(100), CreatedOn datetime, UploadedBy nvarchar(100))
INSERT INTO #temp(TemplateID, TemplateName, CreatedOn, UploadedBy)
SELECT TemplateID,
TemplateName,
CreatedOn,
( [user].LastName + ' ' + [user].FirstName ) AS UploadedBy
FROM Templates
INNER JOIN [user] ON [user].UserID = Templates.CreatedBy
WHERE facilityid = #facilityID
Then:
IF #SortOrder = 1 --'ASC'
BEGIN
IF #sort = 2
Select *
From #Temp
Order by TemplateName ASC
ELSE IF #sort = 3
Select *
From #Temp
Order By CreatedBy ASC
-- and so on...
END
ELSE -- descending
BEGIN
-- Ad. Inf.
END
Delete
From #Temp
WHERE ID < #pageStart or ID > #pageStart + #pageSize
The following SP when runs doesnot
sort records.if i replace 2,3,4 by
columnname,
You shouldn't replace 2, 3, 4 in the ORDER BY clause by the column name. When you call the procedure just pass the column you want to sort by as the 3rd parameter.
EXEC [dbo].[usp_SEL_GetRenderingTemplate] 1,'Ascending','CreatedOn',#vErrorCode
The CASE will then evaluate the query to something like
...ORDER BY 3 DESC
which sorts the query by the 3rd column in the SELECT clause (i.e. CreatedOn)
The problem is that in CASE clauses the return values must have the same data type.
You can work around this problem by using multiple CASE statements http://www.extremeexperts.com/sql/articles/CASEinORDER.aspx
Or casting everything to the same data type.

Dynamic order direction

I writing a SP that accepts as parameters column to sort and direction.
I don't want to use dynamic SQL.
The problem is with setting the direction parameter.
This is the partial code:
SET #OrderByColumn = 'AddedDate'
SET #OrderDirection = 1;
…
ORDER BY
CASE WHEN #OrderByColumn = 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN #OrderByColumn = 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN #OrderByColumn = 'AddedBy' THEN AddedBy
WHEN #OrderByColumn = 'Title' THEN Title
END
You could have two near-identical ORDER BY items, one ASC and one DESC, and extend your CASE statement to make one or other of them always equal a single value:
ORDER BY
CASE WHEN #OrderDirection = 0 THEN 1
ELSE
CASE WHEN #OrderByColumn = 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN #OrderByColumn = 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN #OrderByColumn = 'AddedBy' THEN AddedBy
WHEN #OrderByColumn = 'Title' THEN Title
END
END ASC,
CASE WHEN #OrderDirection = 1 THEN 1
ELSE
CASE WHEN #OrderByColumn = 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN #OrderByColumn = 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN #OrderByColumn = 'AddedBy' THEN AddedBy
WHEN #OrderByColumn = 'Title' THEN Title
END
END DESC
You can simplify the CASE by using ROW_NUMBER which sorts your data and effectively converts it into a handy integer format. Especially since the question is tagged SQL Server 2005
This also expands easily enough to deal with secondary and tertiary sorts
I've used multiplier to again simplify the actual select statement and reduce the chance of RBAR evaluation in the ORDER BY
DECLARE #multiplier int;
SELECT #multiplier = CASE #Direction WHEN 1 THEN -1 ELSE 1 END;
SELECT
Columns you actually want
FROM
(
SELECT
Columns you actually want,
ROW_NUMBER() OVER (ORDER BY AddedDate) AS AddedDateSort,
ROW_NUMBER() OVER (ORDER BY Visible) AS VisibleSort,
ROW_NUMBER() OVER (ORDER BY AddedBy) AS AddedBySort,
ROW_NUMBER() OVER (ORDER BY Title) AS TitleSort
FROM
myTable
WHERE
MyFilters...
) foo
ORDER BY
CASE #OrderByColumn
WHEN 'AddedDate' THEN AddedDateSort
WHEN 'Visible' THEN VisibleSort
WHEN 'AddedBy' THEN AddedBySort
WHEN 'Title' THEN TitleSort
END * #multiplier;
This works fine for me – (where, order by, direction, Pagination)
parameters
#orderColumn int ,
#orderDir varchar(20),
#start int ,
#limit int
select * from items
order by
CASE WHEN #orderColumn = 0 AND #orderdir = 'desc' THEN items.[CategoryName] END DESC,
CASE WHEN #orderColumn = 0 AND #orderdir = 'asc' THEN items.[CategoryName] END ASC,
CASE WHEN #orderColumn = 1 AND #orderdir = 'desc' THEN items.[CategoryValue] END DESC,
CASE WHEN #orderColumn = 1 AND #orderdir = 'asc' THEN items.[CategoryValue] END ASC,
CASE WHEN #orderColumn = 2 AND #orderdir = 'desc' THEN items.[CreatedOn] END DESC,
CASE WHEN #orderColumn = 2 AND #orderdir = 'asc' THEN items.[CreatedOn] END ASC
OFFSET #start ROWS FETCH NEXT #limit ROWS ONLY
Here is an example:
CREATE PROCEDURE GetProducts
(
#OrderBy VARCHAR(50),
#Input2 VARCHAR(30)
)
AS
BEGIN
SET NOCOUNT ON
SELECT Id, ProductName, Description, Price, Quantity
FROM Products
WHERE ProductName LIKE #Input2
ORDER BY
CASE
WHEN #OrderBy = 'ProductNameAsc' THEN ProductName
END ASC,
CASE
WHEN #OrderBy = 'ProductNameDesc' THEN ProductName
END DESC
END
From here:
http://www.dominicpettifer.co.uk/Blog/21/dynamic-conditional-order-by-clause-in-sql-server-t-sql
Ascending and Descending actions need
to be grouped into separate CASE
statements, separated with a comma. In
your server-side code/script make sure
to append 'Asc' or 'Desc' onto the
order by string, or you could have two
Stored procedure input parameters for
column name and order by direction if
you want.
More compact version of accepted answer, but as accepted answer this works fine only when result expressions after THEN have the same type.
ORDER BY
CASE #OrderDirection WHEN 0 THEN
CASE #sortColumn
WHEN 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN 'AddedBy' THEN AddedBy
WHEN 'Title' THEN Title
END
END ASC,
CASE #OrderDirection WHEN 1 THEN
CASE #sortColumn
WHEN 'AddedDate' THEN CONVERT(varchar(50), AddedDate)
WHEN 'Visible' THEN CONVERT(varchar(2), Visible)
WHEN 'AddedBy' THEN AddedBy
WHEN 'Title' THEN Title
END
END DESC
Dynamic sorting in either ASC or DESC order, irrespective of datatype.
The first example sorts alphabetically, the second using numbers. The #direction variable denotes sort direction (0 = ASC or 1 = DESC) and [column] is the sort column.
This also works for multi-column sorting and you can hide the [row] column if placed in a further outer query.
DECLARE #direction BIT = 1 -- 0 = ASC or 1 = DESC
-- Text sort.
SELECT
IIF(#direction = 0, ROW_NUMBER() OVER (ORDER BY [column] ASC), ROW_NUMBER() OVER (ORDER BY [column] DESC)) [row]
, *
FROM
( -- your dataset.
SELECT N'B' [column]
UNION SELECT N'C'
UNION SELECT N'A'
) [data] ORDER BY [row]
-- Numeric sort.
SELECT
IIF(#direction = 0, ROW_NUMBER() OVER (ORDER BY [column] ASC), ROW_NUMBER() OVER (ORDER BY [column] DESC)) [row],
*
FROM
( -- your dataset.
SELECT 2 [column]
UNION SELECT 3
UNION SELECT 1
) [data] ORDER BY [row]