11.07.2015 Views

101 Tech Tips - Visual Studio Magazine - One-Stop Source Shop

101 Tech Tips - Visual Studio Magazine - One-Stop Source Shop

101 Tech Tips - Visual Studio Magazine - One-Stop Source Shop

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>101</strong> TECH TIPSFor <strong>Visual</strong> <strong>Studio</strong> DevelopersSQL Server 6.5 and upLevel: IntermediateUse the CASE Statement in a SQL SELECT ClauseSQL Server provides a mechanism for returning differentvalues in a SELECT clause based on Boolean conditions: theCASE statement. This statement resembles <strong>Visual</strong> Basic’s SelectCase statement.The SQL CASE statement has WHEN, THEN, and ELSE clausesalong with an END terminator. The syntax is:CASE [expression]WHEN [value | Boolean expression] THEN [return value][ELSE [return value]]ENDThe [expression] is optional and contains a table column or avariable. When you specify [expression] directly after the CASE,you must populate the [value] parameter in the WHEN clause:DECLARE @TestVal intSET @TestVal = 3SELECTCASE @TestValWHEN 1 THEN 'First'WHEN 2 THEN 'Second'WHEN 3 THEN 'Third'ELSE 'Other'ENDSQL Server compares this value to the expression and when thevalues match, it returns the THEN clause’s [return value]. If noneof the WHEN clauses equates to true, SQL Server returns the[return value] in the optional ELSE clause. If the ELSE clause isomitted and no value is matched, NULL is returned.If you don’t specify [expression], you must include the [Booleanexpression] in the WHEN clause. This can contain any validBoolean expression SQL Server allows:DECLARE @TestVal intSET @TestVal = 5SELECTCASEWHEN @TestVal

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!