How to add to Where clause depending on parameter value

≡放荡痞女 提交于 2019-12-08 14:02:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!