Using Case in Update Statement
UPDATE dbo.Customer SET stateDescription = CASE WHEN statecode = 'MA' THEN 'Massachusetts' WHEN statecode = 'VA' THEN 'Virginia' WHEN statecode = 'PA' THEN 'Pennsylvania' ELSE NULL END
Using Case in Select Statement
SELECT
COUNT
(*)
AS
TotalCustomers
,
SUM
(
CASE
WHEN
statecode
=
'MA'
THEN
1
ELSE
NULL
END
)
AS
TotalMassCustomers
,
AVG
(
CASE
WHEN
statecode
=
'MA'
THEN
totalsales
ELSE
NULL
END
)
AS
TotalMassSales
FROM
dbo.Customer
Using Case in Stored Procedure
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'
Great article. Your blogs are unique and simple that is understood by anyone.
ReplyDelete