如果参数为空,SQL忽略WHERE的一部分 [英] SQL ignore part of WHERE if parameter is null

查看:585
本文介绍了如果参数为空,SQL忽略WHERE的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于4个参数从表中获取信息的存储过程。

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

我想根据参数获取值,但如果参数为NULL那么不检查该参数。所以如果所有4个参数都为null,我会显示整个表。

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.

这是我的SP(你可以看到,这只适用于1个参数atm) p>

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)?

推荐答案

对于每个可能的组合都有 IF

How about something like

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

您也可以使用

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

但一般来说,类似

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)

这篇关于如果参数为空,SQL忽略WHERE的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆