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.
To set a variable value in SQL server based on true / false result, CASE statements can be used.
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.
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.
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
                        try this:
DECLARE @Test int;
DECLARE @Result char(10);
SET @Test = 10;
select @Result=
CASE @Test
WHEN 10 THEN  'OK test'
END
Print @Result;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With