简体   繁体   English

CASE WHEN SQL 查询在 else 中执行条件,即使第一个条件为真

[英]CASE WHEN SQL Query executes condition in else even if first condition is true

I'm trying to check if data exists in a table.我正在尝试检查表中是否存在数据。 First I check whether the table exists then I use a SELECT statement to check whether the table is empty or not首先我检查表是否存在然后我使用 SELECT 语句来检查表是否为空

DECLARE @dataExists BIT = 0

SELECT 
             @dataExists = CASE 
                               WHEN OBJECT_ID('TableName') IS NULL 
                                  THEN 0 
                                  ELSE CASE 
                                          WHEN EXISTS(SELECT 1 FROM TableName) 
                                             THEN 1 
                                             ELSE 0 
                                       END 
                            END

SELECT @dataExists

I have this query which is not supposed to execute SELECT 1 FROM TableName if OBJECT_ID('TableName') returns NULL but this query goes on and executes如果OBJECT_ID('TableName')返回 NULL,我有这个不应该执行SELECT 1 FROM TableName的查询但是这个查询继续执行

SELECT 1 FROM TableName 

which of course throws an error这当然会引发错误

Invalid Object Name TableName无效的 Object 名称 TableName

Try the following:尝试以下操作:

DECLARE @dataExists BIT = 0

IF OBJECT_ID('TableName') IS NOT NULL
BEGIN
    SET @dataExists = (SELECT TOP 1 1 FROM TableName)
END

SELECT @dataExists

The error you are getting is a compilation error.您得到的错误是编译错误。 Since it's a single statement.因为它是一个单一的声明。 SQL Server needs to build an execution plan, and can't do this, if the table doesn't exists. SQL 服务器需要建立一个执行计划,如果表不存在则不能这样做。

By adding an IF the statement doesn't need to be "compiled" if the condition is not met.通过添加IF ,如果不满足条件,则不需要“编译”该语句。

With dynamic SQL:带动态 SQL:

DECLARE @TableName SysName = 'TableName'
DECLARE @Sql NVARCHAR(MAX) = '
DECLARE @dataExists BIT = 0

IF OBJECT_ID('''+@TableName+''') IS NOT NULL
BEGIN
    SET @dataExists = (SELECT TOP 1 1 FROM '+QUOTENAME(@TableName)+')
END

SELECT @dataExists
'

EXEC (@Sql)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM