Chapter 5 ADVANCED DATA RETRIEVAL AND MODIFICATION 265
Chapter 5 ADVANCED DATA RETRIEVAL AND MODIFICATION 265 CASE Expressions A CASE expression works like an IF statement, but can be used in locations where an IF statement cannot. Specifically, a CASE expression returns one of a specific set of values based on the outcome of one or more expressions. Here s an example: Select CASE datepart(weekday, getdate()) WHEN 1 then Sunday WHEN 2 then Monday WHEN 3 then Tuesday WHEN 4 then Wednesday WHEN 5 then Thursday WHEN 6 then Friday WHEN 7 then Saturday ELSE Unknown END This example gets the day of week for today and turns it into a string that represents the text for the day of week. If, for some reason, the day of the week returned by the datepart function is invalid, it returns the string Unknown. The result is placed into the variable @Result. This is the proper syntax to use when the comparison you want to use is equality in this situation, datepart(weekday, getdate()) = 1. Notice that the expression starts with the keyword CASE and ends with the keyword END. This is the only time you can use an END without a BEGIN. This is called a simple CASE statement, contrasted against the searched CASE statement, discussed later in this section. Now, if you wanted to write code with a similar result, you can write this: DECLARE @result varchar(30) IF datepart(weekday, getdate()) = 1 set @Result = Monday else if datepart(weekday, getdate()) = 2 set @Result = Tuesday else if datepart(weekday, getdate()) = 3 set @result = Wednesday else if datepart(weekday, getdate()) = 4 set @result = Thursday else if datepart(weekday, getdate()) = 5 set @result = Friday else if datepart(weekday, getdate()) = 6 set @result = Saturday else if datepart(weekday, getdate()) = 7 set @result = Sunday else set @result = Unknown PRINT @Result
If you looking for unlimited one inclusive web hosting plan please check cheap web hosting website.