Gene Wirchenko
2012-06-21 16:37:54 UTC
Dear SQLers:
http://www.mssqltips.com/sqlservertip/1455/using-the-case-expression-instead-of-dynamic-sql-in-sql-server/
has an example with some puzzling code. Example 3's code is:
***** Start of Code *****
CREATE PROCEDURE dbo.getCustomerData @sortby VARCHAR(9),
@sortdirection CHAR(4)
AS
SET nocount ON
SELECT customerid, firstname, lastname, statecode, statedescription,
totalsales
FROM dbo.Customer
ORDER BY
CASE @sortdirection
WHEN 'asc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
ASC,
CASE @sortdirection
WHEN 'desc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
DESC
GO
EXEC dbo.getCustomerData 'lastname', 'desc'
***** End of Code *****
This looks like it specifies an order of two columns one
ascending and one descending but with one of them null. How does this
work? The syntax is weird (to me).
Sincerely,
Gene Wirchenko
http://www.mssqltips.com/sqlservertip/1455/using-the-case-expression-instead-of-dynamic-sql-in-sql-server/
has an example with some puzzling code. Example 3's code is:
***** Start of Code *****
CREATE PROCEDURE dbo.getCustomerData @sortby VARCHAR(9),
@sortdirection CHAR(4)
AS
SET nocount ON
SELECT customerid, firstname, lastname, statecode, statedescription,
totalsales
FROM dbo.Customer
ORDER BY
CASE @sortdirection
WHEN 'asc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
ASC,
CASE @sortdirection
WHEN 'desc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
DESC
GO
EXEC dbo.getCustomerData 'lastname', 'desc'
***** End of Code *****
This looks like it specifies an order of two columns one
ascending and one descending but with one of them null. How does this
work? The syntax is weird (to me).
Sincerely,
Gene Wirchenko