【问题标题】:Dynamic where condition in SQL Server stored procedureSQL Server 存储过程中的动态 where 条件
【发布时间】:2021-08-04 20:30:02
【问题描述】:

这是我的 SQL Server 存储过程

CREATE PROC test_sp
@id int,
@ipVal varchar(20) = null,
@browserName varchar(20) = null
as
begin
select * from users where id=@id order by id desc;
end

我想在此动态更改我的where 条件。

@ipVal is not null 时,我应该在 Where 条件下传递所有三个参数。当我的@ipVal is null 时,我应该只在 where 条件下通过id=@id

如何在 SQL Server 存储过程中做到这一点?

【问题讨论】:

标签: sql sql-server mssql-jdbc


【解决方案1】:

你可以把你的 where 子句改成这个:

select * from users 
where id=@id
and (@ipVal is null or (browserName=@browserName and ipval=@ipVal))
 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2015-11-21
    • 2020-10-13
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多