Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : set a variable in CASE statement

Is it possible to set a variable in a case statement? My code doesn't work. Thanks all.

CREATE PROCEDURE spReport @q1 INT, @q2 INT AS BEGIN  -- Dates for the 2 different quarters to be viewed DECLARE @StartDateQ1 DATETIME DECLARE @EndDateQ1 DATETIME DECLARE @StartDateQ2 DATETIME DECLARE @EndDateQ2 DATETIME  SELECT CASE @q1     WHEN 1 THEN SET @StartDateQ1 = '20130401' END 
like image 597
Bobby Avatar asked Nov 26 '13 16:11

Bobby


People also ask

How do you set a variable in a case statement in SQL?

to set the value of a single variable according to a CASE expression. If your real logic is more complicated (e.g. need to set multiple variables inside a condition) look at IF ... ELSE instead. CASE is an expression not a flow of control construct. Show activity on this post.

How do you set a variable value in SQL?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Can you assign variables in the declare statement?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

Can you use a variable in in statement SQL?

You can't use a variable in an IN clause - you need to use dynamic SQL, or use a function (TSQL or CLR) to convert the list of values into a table.


1 Answers

You can use

SET @StartDateQ1 = CASE @q1                      WHEN 1 THEN '20130401'                    END  

to set the value of a single variable according to a CASE expression.

If your real logic is more complicated (e.g. need to set multiple variables inside a condition) look at IF ... ELSE instead.

CASE is an expression not a flow of control construct.

like image 194
Martin Smith Avatar answered Oct 09 '22 11:10

Martin Smith