我希望有人能帮助解释这个SQL子句的最后一行代码行(@Active = 1 ....):
SELECT DISTINCT LOC_ID
,LOC_CODE
,ADDR_LINE_1
,ADDR_LINE_2
,ADDR_LINE_3
,CITY
,STATE
,COUNTRY
,POSTAL_CODE
,COMPANY
,OPERATION_TYPE
,PROCESS
,ADDR_LINE_1 + ',' +ADDR_LINE_2+ ',' + CITY + '-' + COUNTRY + ' ' + POSTAL_CODE AS ADDRESS
,COMPANY + '.' + CENTER + '.' + OPERATION_TYPE + '.' + PROCESS AS Proc_Combo
,CASE WHEN INACTIVE_DATE IS NULL THEN 'Active'
WHEN INACTIVE_DATE IS NOT NULL THEN 'InActive'
ELSE 'UNKNOWN' END AS INACTIVE_DATE
,CASE WHEN INSTANCE_ID = 1 THEN 'AP'
WHEN INSTANCE_ID = 2 THEN 'GAP'
ELSE 'ALL' END AS INSTANCE_ID
FROM HR_Locations
WHERE
(@STATE IS NOT NULL AND STATE =@STATE OR @STATE='' AND STATE =STATE OR @STATE IS NULL AND 1=1)
AND
(@ACTIVE=1 AND INACTIVE_DATE IS NULL OR @ACTIVE=2 AND INACTIVE_DATE IS NOT NULL OR @ACTIVE=0 AND 1=1 OR @ACTIVE IS NULL)
我遇到过这样的代码,只是这不包含在“IF”块中
答案 0 :(得分:3)
重写为
时更容易理解(@ACTIVE=1 AND INACTIVE_DATE IS NULL)
OR (@ACTIVE=2 AND INACTIVE_DATE IS NOT NULL)
OR (@ACTIVE=0 AND 1=1)
OR @ACTIVE IS NULL
我觉得有趣的部分是(@ACTIVE=0 AND 1=1)
。这将AND
条件@ACTIVE=0
,其值为TRUE
。在我看来,这可能是一个错字。我已经看到类似(@ACTIVE=0 OR 1=1)
之类的东西使条件变为“可选”,但在这种情况下它看起来是不必要的。您可以尝试在没有AND 1=1
的情况下运行查询,看看结果是否相同?
答案 1 :(得分:1)
不确定1 = 1是...
@ACTIVE=1 AND INACTIVE_DATE IS NULL OR
@ACTIVE=2 AND INACTIVE_DATE IS NOT NULL OR
@ACTIVE=0 AND 1=1 OR
@ACTIVE IS NULL
似乎where子句正在验证@Active标志和非活动日期,以确保如果状态为活动状态,则非活动状态为空,反之亦然。