I'll admit I've never had to do this before so there was a bit of head scratching involved. Simple example table to demonstrate:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') AND type in (N'U'))
DROP TABLE [dbo].[MyTable]
GO
CREATE TABLE dbo.MyTable
(
col1 INT
, col2 CHAR(1)
)
GO
INSERT dbo.MyTable (col1, col2) VALUES (1, 'A')
INSERT dbo.MyTable (col1, col2) VALUES (1, 'B')
INSERT dbo.MyTable (col1, col2) VALUES (1, 'C')
INSERT dbo.MyTable (col1, col2) VALUES (2, 'A')
INSERT dbo.MyTable (col1, col2) VALUES (2, 'B')
INSERT dbo.MyTable (col1, col2) VALUES (2, 'C')
INSERT dbo.MyTable (col1, col2) VALUES (3, 'A')
INSERT dbo.MyTable (col1, col2) VALUES (3, 'B')
INSERT dbo.MyTable (col1, col2) VALUES (3, 'C')
Using an @SortStyle parameter to differentiate between sort orders, @SortStyle =1 will sort by col1 ASC, col2 DESC
and @SortStyle=2 sort by col2 DESC, col1 ASC
.
DECLARE @SortStyle INT
SET @SortStyle = 1
SELECT
col1
, col2
FROM
dbo.MyTable
ORDER BY
CASE
WHEN @SortStyle = 1 THEN col1
END ASC,
CASE
WHEN @SortStyle = 1 THEN col2
END DESC,
CASE
WHEN @SortStyle = 2 THEN col2
END DESC,
CASE
WHEN @SortStyle = 2 THEN col1
END ASC
SET @SortStyle = 2
SELECT
col1
, col2
FROM
dbo.MyTable
ORDER BY
CASE
WHEN @SortStyle = 1 THEN col1
END ASC,
CASE
WHEN @SortStyle = 1 THEN col2
END DESC,
CASE
WHEN @SortStyle = 2 THEN col2
END DESC,
CASE
WHEN @SortStyle = 2 THEN col1
END ASC
How do you ORDER BY a parameter covers the simpler case of sorting by just 1 column.
CASE
can be applicable to this case.