带where子句的null和case语句的SQL查询

时间:2018-09-12 09:27:25

标签: sql tsql

DECLARE @AuditTypeID BIGINT=NULL
DECLARE @ChecklistTypeID BIGINT = NULL


SELECT * FROM TmpChecklist WHERE ChecklistTypeID IN 
          (CASE WHEN (@AuditTypeID IS NOT NULL) THEN (select distinct ChecklistTypeID from TmpChecklist where checklistTypeID IN 
                (SELECT checklistTypeID FROM TmpChecklist WHERE AudittypeID=@AuditTypeID AND (@ChecklistTypeID IS NULL OR @ChecklistTypeID = '') 
                UNION SELECT @ChecklistTypeID))
                ELSE
                (SELECT DISTINCT checklistTypeID FROM TmpChecklist WHERE checklistTypeID IN (ISNULL(@checklistTypeID,checklistTypeID) ))
          END)

这两个变量都可以为null或可以为null或都可以不为null

因此,如果@AuditTypeID不为空,那么我想基于ChecklistTypeID选择@AuditTypeID,否则请选择所有ChecklistTypeID(同样,如果@ChecklistTypeID为null,则选择所有ChecklistTypeID,否则基于@ChecklistTypeID

我正在尝试上述查询,但是出了点问题。

我该如何实现?

2 个答案:

答案 0 :(得分:0)

您不能在where子句中使用大小写,您可以像下面这样编写查询

DECLARE @AuditTypeID BIGINT=NULL
DECLARE @ChecklistTypeID BIGINT = NULL


SELECT * FROM TmpChecklist WHERE  (@AuditTypeID IS NOT NULL and
ChecklistTypeID IN  
(select distinct ChecklistTypeID from TmpChecklist where 
 checklistTypeID IN 
                (SELECT checklistTypeID FROM TmpChecklist WHERE AudittypeID=@AuditTypeID
                                        AND (@ChecklistTypeID IS NULL OR @ChecklistTypeID = '') 
                UNION SELECT @ChecklistTypeID)
))
                OR
ChecklistTypeID in
                (SELECT DISTINCT checklistTypeID FROM TmpChecklist WHERE checklistTypeID IN coalesce(@checklistTypeID,checklistTypeID))

答案 1 :(得分:0)

我认为您想要的逻辑比您正在做的要简单一些:

SELECT cl.*
FROM TmpChecklist cl
WHERE (@AuditTypeID IS NULL OR cl.AudittypeID = @AuditTypeID) AND
      (@ChecklistTypeID IS NULL OR cl.ChecklistTypeID = @ChecklistTypeID);