我有一个我想运行的SQL查询,并且如果我将参数标记为true,则想要向where子句添加内容。我不认为我需要两次相同的sql语句,但找不到这样做的方法。这就是我要的。
DECLARE @getShipped VARCHAR = 'false';
SELECT DISTINCT
Serial_No
INTO #Serials
FROM Part_v_Container_Change2 AS CC
WHERE Change_Date <= @dateEnding
*** AND IF @getShipped = 'true' THEN CC.Container_Status = 'Shipped' ***
尝试过if语句和case语句但似乎无法使其工作?如果我没有,我只是不想重复sql。
答案 0 :(得分:6)
尝试这样
DECLARE @getShipped VARCHAR(20) = 'false';
SELECT DISTINCT
Serial_No
INTO #Serials
FROM Part_v_Container_Change2 AS CC
WHERE Change_Date <= @dateEnding AND
((@getShipped = 'true' AND CC.Container_Status = 'Shipped') OR @getShipped = 'false')
答案 1 :(得分:0)
尝试动态sql,如下所示
DECLARE @getShipped VARCHAR(20) = 'false';
DECLARE @sql NVARCHAR(255) = 'SELECT DISTINCT Serial_No INTO #Serials FROM Part_v_Container_Change2 AS CC
WHERE Change_Date <= ''' + + CONVERT(VARCHAR, @dateEnding, 101) + ''''
DECLARE @filter NVARCHAR(50) = ' AND CC.Container_Status = ''Shipped'''
IF @getShipped = 'true'
SET @sql = @sql + @filter
EXEC (@sql)