How to ignore a parameter in stored procedure if its value is null

后端 未结 3 1361
遥遥无期
遥遥无期 2021-01-17 03:24

I have a stored procedure in which I have to join 10 tables and use WHERE condition to filter the records based on the parameters passed in the stored procedure

3条回答
  •  旧时难觅i
    2021-01-17 04:02

    There is a very good article Dynamic Search Conditions in T‑SQL by Erland Sommarskog. He explains several approaches that could be used and compares building dynamic SQL as @lad2025 suggested and using OPTION(RECOMPILE).

    I personally use OPTION(RECOMPILE) in these queries. You use SQL Server 2008, so this option is a good choice. If you do go via the dynamic SQL route, make sure to read his another article The Curse and Blessings of Dynamic SQL.

    So, your procedure becomes something like this:

    create procedure proc1
        @var1 varchar(100) = null,
        @var2 varchar(100) = null,
        @var3 varchar(100) = null,
        @var4 varchar(100) = null,
        ........   
        @var10 varchar(100) = null
    as
    begin
        insert into #a
        select * from
        (
            select * 
            from
                tab1 as a
                inner join tab2 as b on a.rollnumber = b.rollnumber
                inner join tab3 as c on c.city = b.city
                ........
                inner join tab10 as j on J.id = i.id
            where 
                (a.id = @var1 OR @var1 IS NULL)
                and (b.id = @var2 OR @var2 IS NULL)
                and (c.id = @var3 OR @var3 IS NULL)
                ...........
                and (J.id = @var10 OR @var10 IS NULL)
        ) as abc
        OPTION(RECOMPILE);
    
        if (select count(*) from #a) < 10 
        begin
            select * from #a
        end
        else 
        begin
            print 'Cannot display the records as count is more than 10'
        end
    end
    

    By the way, it is not clear what you are trying to achieve by checking the count(), but maybe all you need is simple TOP(10) to return at most 10 first rows. Make sure to add ORDER BY clause if you do use TOP to return results consistently. If you didn't know, you can have another parameter of your procedure to indicate the maximum number of rows to return and use it in TOP(@ParamMaxRowCount). It is not common to have a stored procedure that sometimes returns result set and sometimes only prints a message.

提交回复
热议问题