用户登录
用户注册

分享至

SQL CASE 和局部变量

  • 作者: 半脸妆_晴儿
  • 来源: 51数据库
  • 2022-10-20

问题描述

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

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;

我使用 MS SQL 2008.

I use MS SQL 2008.

推荐答案

在 MSSQL 这个场景中使用 CASE 的两种方式

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
软件
前端设计
程序设计
Java相关