ISNULL,IIF,CASE语句中的子查询

时间:2015-08-21 14:29:08

标签: sql sql-server subquery isnull iif

在ISNULL或IIF或CASE中作为参数提供的子查询无论条件如何都会被执行

要解释我的意思,请考虑以下示例。当我运行以下查询并查看执行计划时,我发现即使变量@Id不为NULL,第二个条件也会始终执行。

任何人都可以解释为什么子查询在查询1,2,3中执行?

--Create a Temp table
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable
CREATE TABLE #TempTable
(
ID INT
)

--Insert some data
INSERT INTO #TempTable VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)

DECLARE @Id INT = 1

--Query 1: ISNULL
SET @Id= ISNULL(@Id, (SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1))
SELECT @Id AS ID

--Query 2: IIF
SET @Id=  IIF(@Id IS NULL,(SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1),@Id)
SET @Id=  IIF(@Id IS NOT NULL,@Id,(SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1))

SELECT @Id AS ID

--Query 3: CASE
SET @Id=  CASE WHEN @Id IS NULL THEN (SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1) ELSE @Id END
SET @Id=  CASE WHEN @Id IS NOT NULL THEN @Id ELSE (SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1)  END
SELECT @Id AS ID

---Query 4: IF
IF @Id IS NULL
BEGIN
    SET @Id = (SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1) 
    SELECT @Id AS ID
END
ELSE 
BEGIN
    SELECT @Id AS ID
END

1 个答案:

答案 0 :(得分:-1)

如果您希望子查询仅在满足空条件时执行,请使用IF代替ISNULL

if @Id is null
   set @id = (SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1)

而不是

SET @Id= ISNULL(@Id, (SELECT TOP 1 ID FROM #TempTable TT WHERE TT.ID = 1))