Ignoring a NULL parameter in T-SQL

后端 未结 10 960
余生分开走
余生分开走 2020-12-03 01:40

I want to be able to pass in a list of parameters, and ignore the ones which are NULL. So that the query is in effect pretending that the filter isn\'t there and ignoring it

10条回答
  •  忘掉有多难
    2020-12-03 01:59

    Thanks, This was helpful. I have decided to use the sp_ExecuteSQL method due to the potential performance advantages mentioned. I have a slightly different take on it which you may find helpful.

    DECLARE @sql nvarchar(4000) 
    DECLARE @where nvarchar(1000) =''
    
    SET @sql = 'SELECT * FROM MyTable'
    
    IF @Param1 IS NOT NULL 
        SET @where = @where + ' AND Field1 = @Param1'
    
    IF @Param2 IS NOT NULL 
        SET @where = @where + ' AND Field2 = @Param2' 
    
    IF @Param3 IS NOT NULL 
        SET @where = @where + ' AND Field3 = @Param3' 
    
    -- Add WHERE if where clause exists, 1=1 is included because @where begins with AND
    IF @where <> ''
        SET @sql = @sql + ' WHERE 1=1' + @where
    
    --Note that we could also create order parameters and append here
    SET @sql = @sql + ' ORDER BY Field1'
    

提交回复
热议问题