SQL ignore part of WHERE if parameter is null

后端 未结 7 616
既然无缘
既然无缘 2020-12-15 15:59

I have a stored procedure that fetches info from a table based on 4 parameters.

I want to get values based on the parameters, but if a parameter is NULL then that pa

7条回答
  •  佛祖请我去吃肉
    2020-12-15 16:51

    If you mean @param1 is parameter for col1, @param2 is parameter for col2,... etc You can try this:

    CREATE PROCEDURE myProcedure
    @Param1 nvarchar(50),
    @Param2 nvarchar(50),
    @Param3 nvarchar(50),
    @Param4 nvarchar(50)
    AS
    BEGIN
    declare @query nvarchar(4000)
    SET @query='SELECT Id, col1, col2, col3, col4 FROM myTable '+
        (case when ((@Param1 is null) and (@Param2 is null) and (@Param3 is null) and (@Param4 is null))
        then ''
        else
            'where '+
            (case when @Param1 is not null
            then ' col1 like '''+@param1+'%'''+
                (case when @param2 is not null then ' AND ' else '' end)
            else '' end)+
            (case when @Param2 is not null
            then ' col2 like '''+@param2+'%'''+
                (case when @param3 is not null then ' AND ' else '' end)
            else '' end)+
            (case when @Param3 is not null
            then ' col3 like '''+@param3+'%'''+
                (case when @param4 is not null then ' AND ' else '' end)
            else '' end)+
            (case when @Param4 is not null
            then ' col4 like '''+@param4+'%'''
            else '' end)
        end)
    
    exec sp_sqlexec @query
    

提交回复
热议问题