问题
I have an sql query that I am wanting to run and want to add something to the where clause if I mark a parameter as true. I didn't think I would need to have the same sql statement twice, but can't find a way to do this. This is what I want.
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' ***
Have tried if statements and case statements but can't seem to get this to work? I just don't want to repeat sql if I don't have too.
回答1:
Try it like this
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')
回答2:
Try dynamic sql something like below
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)
来源:https://stackoverflow.com/questions/34730633/how-to-add-to-where-clause-depending-on-parameter-value