Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL CASE和局部变量_Sql_Sql Server_Tsql_Sql Server 2008 - Fatal编程技术网

SQL CASE和局部变量

SQL CASE和局部变量,sql,sql-server,tsql,sql-server-2008,Sql,Sql Server,Tsql,Sql Server 2008,我想知道如何在SQL中的CASE语句中使用局部变量 此脚本给了我一个错误: DECLARE @Test int; DECLARE @Result char(10); SET @Test = 10; CASE @Test WHEN @Test = 10 THEN SET @Result='OK test' END Print @Result; 我使用MS SQL 2008。在SQL Server中,我将这样编写: DECLARE

我想知道如何在SQL中的
CASE
语句中使用局部变量

此脚本给了我一个错误:

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

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

我使用MS SQL 2008。

在SQL Server中,我将这样编写:

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

SET @Result = CASE @Test
WHEN 10
 THEN 'OK test'
END
Print @Result;
WHEN
子句没有
@Test=10
,因为
@Test
变量在
CASE
子句中有说明


请参阅SQL Server的文档。

CASE@Test WHEN 10然后

使用MSSQL在本场景中使用CASE的两种方法

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
对于SQL server 2005,请尝试以下操作:

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

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

Print @Result;

这在我的SQL 2005数据库中不起作用。(关键字“Case”附近的语法不正确)。(我有相同的解决方案,但不起作用)。这里的语法是错误的。不能像if语句那样使用case语句。anishmarokey的答案更简洁,因为它保留了@result变量。他们是否删除了名称的“服务器”部分-P
DECLARE @Test int;
DECLARE @Result char(10);
SET @Test = 10;

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

Print @Result;