SQL CASE 和局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3403390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:05:11  来源:igfitidea点击:

SQL CASE and local variables

sqlsql-servertsqlsql-server-2008

提问by GibboK

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

我想知道如何CASE在 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.

我使用 MS SQL 2008。

回答by Evil Pigeon

Two ways to use CASE in this scenario with MSSQL

在这个场景中使用 CASE 和 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

回答by anishMarokey

try this:

尝试这个:

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

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

Print @Result;

回答by Oded

In SQL Server I would write it like this:

在 SQL Server 中,我会这样写:

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

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

The WHENclause does not have @Test = 10, as the @Testvariable is stated in the CASEclause.

WHEN子句没有@Test = 10,因为子句中@Test声明了变量CASE

See the CASEdocumentation for SQL Server.

请参阅CASESQL Server的文档。

回答by nw.

CASE @Test WHEN 10 THEN

案例@Test 10 THEN

回答by Tobiasopdenbrouw

DECLARE @Test int;
SET @Test = 10;

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

For SQL server 2005

对于 SQL Server 2005