我有一张这样的桌子:
+-------------+--------------------------------------+--------------------------------------+---------------+
| BackCheckId | TaskId | EmpGuid | CompletedDate |
+-------------+--------------------------------------+--------------------------------------+---------------+
| 1 | B92F7079-2011-44D6-B3C4-BD2F7481C97F | 6074CAEA-7A8E-4699-9451-16C2EAF394EF | NULL |
| 2 | 82AB0C4B-9342-46FA-ACBE-C00B87571BF9 | 6074CAEA-7A8E-4699-9451-16C2EAF394EF | NULL |
+-------------+--------------------------------------+--------------------------------------+---------------+
查询创建:
CREATE TABLE Backchecks(
BackCheckId int,
TaskId UNIQUEIDENTIFIER,
EmpGuid UNIQUEIDENTIFIER,
CompletedDate DATETIME
);
INSERT INTO Backchecks VALUES
(1, 'B92F7079-2011-44D6-B3C4-BD2F7481C97F', '6074CAEA-7A8E-4699-9451-16C2EAF394EF',NULL),
(2, '82AB0C4B-9342-46FA-ACBE-C00B87571BF9','6074CAEA-7A8E-4699-9451-16C2EAF394EF',NULL)
我要做的是根据currentEmpGuid
过滤此数据,因此我声明变量以对其进行测试:
DECLARE @CurrentEmpGuid UNIQUEIDENTIFIER = 'CC713AC9-ED79-47E3-BA37-47F2D5009BFC'
DECLARE @FilterEmpKey INT = NULL
SELECT * FROM Backchecks AS BC
WHERE [BC].[CompletedDate] IS NULL
AND (@FilterEmpKey IS NULL
OR [BC].[EmpGuid] = @CurrentEmpGuid)
因此,您可以看到它不应返回任何结果,因为BC.EmpGuid
不等于表中的任何结果,但是由于某种原因,我得到了结果。我在做什么错了?
答案 0 :(得分:5)
BC.EmpGuid不等于表中的任何结果,但是由于某种原因,我得到了结果。我在做什么错了?
WHERE [BC].[CompletedDate] IS NULL
对于两行和
(@FilterEmpKey IS NULL
OR [BC].[EmpGuid] = @CurrentEmpGuid)
由于@FilterEmpKey为NULL,所有行的均为TRUE。仅当您将@FilterEmpKey设置为某些非空值时,才需要评估[BC].[EmpGuid] = @CurrentEmpGuid
。