SQL CASE and local variables

后端 未结 5 1243
忘了有多久
忘了有多久 2021-02-07 23:47

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;
    DE         


        
相关标签:
5条回答
  • 2021-02-08 00:21

    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
    
    0 讨论(0)
  • 2021-02-08 00:25
    DECLARE @Test int;
    SET @Test = 10;
    
    SELECT 
    CASE @Test
    WHEN 10
    THEN 'OK test'
    END
    

    For SQL server 2005

    0 讨论(0)
  • 2021-02-08 00:30

    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.

    0 讨论(0)
  • 2021-02-08 00:31

    try this:

    DECLARE @Test int;
    DECLARE @Result char(10);
    SET @Test = 10;
    
    select @Result=
    CASE @Test
    WHEN 10 THEN  'OK test'
    END
    
    Print @Result;
    
    0 讨论(0)
  • 2021-02-08 00:31

    CASE @Test WHEN 10 THEN

    0 讨论(0)
提交回复
热议问题