我试图使用应用程序传递的参数来确定查询中的WHERE子句。根据参数中的值,它将确定WHERE。 3个WHERE选项中的2个导致NULL的评估。 3个潜在的WHERE语句如下所示,每个语句在独立应用时都有效。
WHERE sSC.Description IS NOT NULL
WHERE sSC.Description IS NULL
WHERE sSC.Description = @Signature
我试图执行这多个变体,但都有不正确的语法。这是最新的。
DECLARE @Signature AS VARCHAR (max)
SET @Signature = 'XXXPARAMETER1XXX'
Select *
FROM Operations.dbo.sSignatureClassification AS sSC
WHERE
CASE @Signature
WHEN 'Without' THEN (sSC.Description IS NOT NULL)
WHEN 'With' THEN (sSC.Description IS NULL)
ELSE (sSC.Description = @Signature)
END
答案 0 :(得分:0)
这将有效:
WHERE (@Signature = 'Without' AND sSC.Description IS NOT NULL)
OR (@Signature = 'With' AND sSC.Description IS NULL)
OR (@Signature <> 'Without' AND @Signature<>'With' AND sSC.Description = @Signature)
但是,您应该考虑分离出查询,因为如果查询计划被缓存,它可能会发现它执行次优。
如果这是在存储过程中,您应该将其分解为:
DECLARE @Signature AS VARCHAR (max)
SET @Signature = 'XXXPARAMETER1XXX'
IF (@Signature = 'With')
SELECT *
FROM Operations.dbo.sSignatureClassification AS sSC
WHERE sSC.Description IS NULL
ELSE
IF (@Signature = 'Without')
Select *
FROM Operations.dbo.sSignatureClassification AS sSC
WHERE sSC.Description IS NOT NULL
ELSE
Select *
FROM Operations.dbo.sSignatureClassification AS sSC
sSC.Description = @Signature
这将导致SQL服务器生成3个单独的查询计划,可能前两个将使用索引扫描(查找null / not null),而最后一个将使用索引搜索。实际上第一个也可能使用索引搜索。检查SQL事件探查器以确保。
答案 1 :(得分:0)
在你需要条件的地方,在你的情况下,我建议使用简单的OR:
DECLARE @Signature AS VARCHAR (max)
SET @Signature = 'XXXPARAMETER1XXX'
Select *
FROM Operations.dbo.sSignatureClassification AS sSC
WHERE
(@Signature= 'Without' AND sSC.Description IS NOT NULL) OR
(@Signature= 'With' AND sSC.Description IS NULL) OR
(@Signature<> 'Without' AND @Signature<> 'With' AND sSC.Description = @Signature)