IF ... ELSE条件总是返回ELSE条件

时间:2018-08-14 19:32:27

标签: sql-server tsql

我有一个简单的查询,如下所示:

@DesignKey [INT] = NULL
AS
        BEGIN
            -- SET NOCOUNT ON added to prevent extra result sets from
            -- interfering with SELECT statements.
            SET NOCOUNT ON;

            -- Insert statements for procedure here
            IF(@DesignKey != NULL)
            BEGIN
                 SELECT
                     [P].[LegacyKey] AS [Job No]
                   , [TT].[Name] AS [Task]
                   , CONCAT([E].[FirstName] , ' ' , [E].[MaidenName]) AS [Technician]
                    FROM [Task] AS [T]
                        LEFT JOIN [TaskAssignation] AS [TA] ON [T].[TaskAssignationId] = [TA].[TaskAssignationId]
                        LEFT JOIN [Employee] AS [E] ON [TA].[EmpKey] = [E].[EmpKey]
                        INNER JOIN [TaskType] AS [TT] ON [T].[TaskTypeId] = [TT].[TaskTypeId]
                        INNER JOIN [Design] AS [D] ON [T].[DesignKey] = [D].[DesignKey]
                        INNER JOIN [ProjectDesign] AS [PD] ON [D].[DesignKey] = [PD].[DesignKey]
                        INNER JOIN [Project] AS [P] ON [PD].[ProjectKey] = [P].[ProjectKey]
                    WHERE [E].[EmpKey] IS NOT NULL
                         AND [T].[DesignKey] = @DesignKey
            END
               ELSE
            BEGIN
                             SELECT
                    [P].[LegacyKey] AS [Job No]
                   , [TT].[Name] AS [Task]
                   , CONCAT([E].[FirstName] , ' ' , [E].[MaidenName]) AS [Technician]
                    FROM [Task] AS [T]
                        LEFT JOIN [TaskAssignation] AS [TA] ON [T].[TaskAssignationId] = [TA].[TaskAssignationId]
                        LEFT JOIN [Employee] AS [E] ON [TA].[EmpKey] = [E].[EmpKey]
                        INNER JOIN [TaskType] AS [TT] ON [T].[TaskTypeId] = [TT].[TaskTypeId]
                        INNER JOIN [Design] AS [D] ON [T].[DesignKey] = [D].[DesignKey]
                        INNER JOIN [ProjectDesign] AS [PD] ON [D].[DesignKey] = [PD].[DesignKey]
                        INNER JOIN [Project] AS [P] ON [PD].[ProjectKey] = [P].[ProjectKey]
                    WHERE [E].[EmpKey] IS NOT NULL

            END
        END

如您所见,它将根据@DesignKey是否为null来执行不同的选择,因此我以以下方式执行查询:

exec usp_Get_EmpoyeeByDesign 

它可以正常运行,如果我将@DesignKey发送为:

exec usp_Get_EmpoyeeByDesign @DesignKey = 2837

它加载了相同的结果,没有考虑我的if条件,我测试了它在where子句中发送designKey参数的情况:

WHERE [E].[EmpKey] IS NOT NULL
                         AND [T].[DesignKey] = 2837

并引发期望结果。因此,总而言之,查询不验证@DesignKey是否到来。那里怎么了问候

1 个答案:

答案 0 :(得分:6)

!= NULL替换为IS NOT NULL

任何使用NULL的操作都将返回NULL,而不是True。

将NULL视为“我不知道”。

你有两个篮子的苹果。其中一个有7个苹果。另一个篮子被盖住了,所以您不知道有多少个苹果。两个篮子的苹果数相同吗?他们有不同数量的苹果吗?

declare @a int, @b int
set @a = 7    -- 7 apples
set @b = NULL -- I don't know how many apples

if @a = @b 
  print 'Equal' -- doesn't print

if @a <> @b 
  print 'Not equal' -- doesn't print

由于您不知道第二个存储桶中有多少个苹果,因此不知道苹果的数量是否相等,也不知道它们是否不相等。