Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

database - SQL ignore part of WHERE if parameter is null

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 parameter isn't checked. So if all 4 parameters is null I would show the entire table.

This is my SP (as you can see, this only works for 1 parameter atm):

CREATE PROCEDURE myProcedure
    @Param1 nvarchar(50),
    @Param2 nvarchar(50),
    @Param3 nvarchar(50),
    @Param4 nvarchar(50)
AS
BEGIN
    IF(@Param1 IS NULL)
        BEGIN
            SELECT Id, col1, col2, col3, col4 FROM myTable
        END
    ELSE
        BEGIN
            SELECT Id, col1, col2, col3, col4 FROM myTable WHERE col1 LIKE @Param1+'%'
        END
END

Is there some way to do this without having a IF for every possible combination (15 IFs)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about something like

SELECT Id, col1, col2, col3, col4 
FROM    myTable 
WHERE   col1 LIKE @Param1+'%'
OR      @Param1 IS NULL

in this specific case you could have also used

SELECT Id, col1, col2, col3, col4 
FROM    myTable 
WHERE   col1 LIKE ISNULL(@Param1,'')+'%'

But in general you can try something like

SELECT Id, col1, col2, col3, col4 
FROM    myTable 
WHERE   (condition1 OR @Param1 IS NULL)
AND     (condition2 OR @Param2 IS NULL)
AND     (condition3 OR @Param3 IS NULL)
...
AND     (conditionN OR @ParamN IS NULL)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...