如果参数为空,SQL 将忽略 WHERE 的一部分 [英] SQL ignore part of WHERE if parameter is null
本文介绍了如果参数为空,SQL 将忽略 WHERE 的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基于 4 个参数从表中获取信息的存储过程.
I have a stored procedure that fetches info from a table based on 4 parameters.
我想根据参数获取值,但如果参数为 NULL,则不会检查该参数.因此,如果所有 4 个参数都为空,我将显示整个表格.
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):
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
有没有什么方法可以为每个可能的组合(15个IF)设置IF
?
Is there some way to do this without having a IF
for every possible combination (15 IFs)?
推荐答案
怎么样
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)
这篇关于如果参数为空,SQL 将忽略 WHERE 的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文