繁体   English   中英

SQL Server存储过程基于输入参数值

[英]SQL Server stored procedure based on input parameters value

create procedure sp1
(
    @p1 int = null
)
as
begin
    select f1, f2, f3 
    from table1;
end

仅当@ p1不为null时,如何将“ where”子句添加到选择查询(where f1 = @ p1)? 如果@ p1为null,则返回所有行!

尝试这个。 仅当@p1 is not null时, where clause才有效

SELECT f1,
       f2,
       f3
FROM   dbo.table1
WHERE  @p1 IS NOT NULL
       AND f1 = @p1 

如果您要在@ p1为null时返回所有值,则只需一个ISNULL函数即可。 如果@ p1 Not Null则将返回f1=@p1值,否则将返回所有值。 尝试这个

SELECT f1,
       f2,
       f3
FROM   dbo.table1
WHERE  f1 = isnull(@p1,f1) 
create procedure dbo.sp1
(
    @p1 int = null
)
as
begin
select f1, f2, f3 
from dbo.table1 where(@p1 is not null and f1=@p1)
end

要么

您可以使用

如果@p1为null,则此处查询返回所有行(因为@ p1为NULL时返回true

  create procedure dbo.sp1
(
    @p1 int = null
)
as
begin
select f1, f2, f3 
from dbo.table1 where(@p1 is null OR f1=@p1)
end

如果@ p1为null,则下面将返回所有内容,如果有值,它将应用条件。

 WHERE @p1 is NULL OR f1=@p1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM