Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL CASE and local variables

I would like to know how I can use local variables in CASE statements in SQL?

This script gives me an error:

    DECLARE @Test int;
    DECLARE @Result char(10);
    SET @Test = 10;

    CASE @Test
    WHEN @Test = 10
    THEN SET @Result='OK test'
    END
    Print @Result;

I use MS SQL 2008.

like image 279
GibboK Avatar asked Aug 04 '10 07:08

GibboK


People also ask

Can we use variable in case statement in SQL?

To set a variable value in SQL server based on true / false result, CASE statements can be used.

How do you declare a local variable in SQL?

SQL Variable declarationThe DECLARE statement is used to declare a variable in SQL Server. In the second step, we have to specify the name of the variable. Local variable names have to start with an at (@) sign because this rule is a syntax necessity. Finally, we defined the data type of the variable.

Can you use CASE when in a where clause?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.


2 Answers

Two ways to use CASE in this scenario with MSSQL

DECLARE 
    @test   int,
    @result char(10)

SET @test = 10

SET @result = CASE @test
    WHEN 10 THEN 
        'OK test'
    ELSE
        'Test is not OK'
END

PRINT @result;

SET @result = CASE 
    WHEN @test = 10 THEN 
        'OK test'
    ELSE
        'Test is not OK'
END

PRINT @result
like image 66
Evil Pigeon Avatar answered Oct 15 '22 23:10

Evil Pigeon


try this:

DECLARE @Test int;
DECLARE @Result char(10);
SET @Test = 10;

select @Result=
CASE @Test
WHEN 10 THEN  'OK test'
END

Print @Result;
like image 25
anishMarokey Avatar answered Oct 15 '22 22:10

anishMarokey