views:

46

answers:

5

Hi, I am studying SQL, I would like to know how can I use local variables in CASE statements in SQL. Thanks guys for your help. This script gives me 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

A: 

In SQL Server I would write it like this:

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

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

The WHEN clause does not have @Test = 10, as the @Test variable is stated in the CASE clause.

See the CASE documentation for SQL Server.

Oded
This does not work in my SQL 2005 db. (incorrect syntax near the keyword 'Case'). (I had the same solution, but it didn't work).
Tobiasopdenbrouw
it gives errors
GIbboK
The syntax here is wrong. You can't use a case statement like an if statement.
Evil Pigeon
The edit fixes it.
Tobiasopdenbrouw
@Tobiasopdenbrouw, @GIbboK, @Evil Pigeon - answer corrected...
Oded
A: 

CASE @Test WHEN 10 THEN

nw
+4  A: 

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
Evil Pigeon
A: 
DECLARE @Test int;
SET @Test = 10;

SELECT 
CASE @Test
WHEN 10
THEN 'OK test'
END

For SQL server 2005

Tobiasopdenbrouw
anishmarokey's answer is a bit cleaner as it retains your @result variable.
Tobiasopdenbrouw
+1  A: 

try this:

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

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

Print @Result;
anishmarokey