sql-server - 检查输入参数是否为 Null 并在 SQL Server 中的位置使用它

标签 sql-server sql-server-2008 null where-clause coalesce

WHERE 子句中包含输入参数但如果它为空则将其排除的最佳方法是什么?

我相信的方式有很多种,但当时我似乎记不起来了。

我还可以使用COALESCE()吗?但我认为这仅适用于选择值?

编辑

为了澄清,假设有一个名为 @code ="1" 的变量,那么我的 where 将为 Where type='B' AND code = @code 但如果 @code is null 那么我只想要 Where type='B' - 请注意缺少的 code = @code

最佳答案

您可以使用IsNull

 where some_column = IsNull(@yourvariable, 'valueifnull')

编辑:

您在评论中所描述的可以这样做:

where (@code is null or code = @code)

关于sql-server - 检查输入参数是否为 Null 并在 SQL Server 中的位置使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4224991/

相关文章:

sql-server - SQL Server 数据库的兼容级别

sql - T-SQL正则表达式替换

sql-server - 仅当使用 IIS Express 或 Kestrel 时,Dotnet 核心应用程序无法使用 IIS 连接到 SQL Server

sql-server-2008 - 提取SSIS中的不同记录

sql - 锁升级 - 这里发生了什么?

sql-server - 在没有 SqlDependency 的情况下根据查询通知运行存储过程

sql-server-2008 - SQL Server : Insert stored procedure results into table based on parameters

javascript - 如何过滤掉空的 JSON 键(null?)

c# - MEF 导入为空

java - Optional.ofNullable() 是否应该用于空检查?