You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL Server 2022条件为假时仍执行后续语句问题

SQL Server 2022 条件分支执行异常问题

在SQL Server 2022 v16.0.4095.4版本中出现异常:即使条件判断为false,对应分支内的语句仍被执行,引发错误。而在SQL Server 2008 (v10.50.4042.0)版本中运行正常,结果符合预期。

复现代码

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[fnInner] 
    (@id uniqueidentifier, @date datetime) 
RETURNS integer 
AS
BEGIN
    IF @id IS NULL
       RETURN CAST('null @id' AS int);

    IF @date IS NULL
       RETURN CAST('null @date' AS int);

    RETURN 1;
END
GO

CREATE FUNCTION [dbo].[fnOuter] 
    (@id uniqueidentifier) 
RETURNS varchar(10) 
AS
BEGIN
    DECLARE @case integer, @test int, @ret varchar(10);
    
    SELECT @case = 2, @test = NULL, @ret = 'None';

    IF @case = 1
        SET @test = dbo.fnInner(@id, NULL);
    ELSE IF @case = 2
        SET @ret = 'Two';
    ELSE IF @test IS NULL
        SET @ret = 'Null';

    RETURN @ret
END
GO

SELECT dbo.fnOuter(NEWID());

结果对比

  • 预期结果:'Two'
  • 实际报错:

Conversion failed when converting the varchar value 'null @date' to data type int

在SQL Server 2008中,fnOuter里@case=2会直接进入对应分支返回'Two',不会执行调用fnInner的代码;但SQL Server 2022中,即使条件不满足,fnInner的调用似乎被提前解析执行,触发了字符串转int的转换错误。

内容的提问来源于stack exchange,提问作者RJBreneman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:31:09