【发布时间】:2023-03-05 03:29:01
【问题描述】:
我正在使用 SQL 2008R2。我有一个包含 56 个可选参数的存储过程。前端应用程序使用它来搜索表。许多列包含 NULL 或空字符串。 当应用程序将“%”作为一个参数的值传递时,sproc 返回与该列的所有非空值匹配的行。要求是返回所有非空和空匹配行(即所有行)。为了模拟它,我有这个小示例代码:
-- table
declare @foobar table
(
column1 nvarchar(100)
, column2 nvarchar(100)
)
-- dummy data
insert into @foobar(column1, column2)
select '100', 'high' union
select '200', 'low' union
select '300', null union
select '400', 'medium' union
select '500', '' union
select '600', 'high' union
select '700', '' union
select '800', null
-- parameter
declare @column2 nvarchar(100)
set @column2 = '%'
-- This returns all non-null values.
-- Requirement is to return all non-null and NULL values.
select column1, column2 from @foobar
where (column2 like @column2 + '%' or nullif(@column2, '') is null)
/*
'%' returns all records where value is not null
Problem: Dev requires all values including null ones.
Thought about the followings:
1. Do a dynamic SQL based query and use sp_executesql:
-- create the WHERE clause
if @Column2 = '%'
@WHERE = 'AND (column2 like @column2 OR column is null)'
else
@WHERE = 'AND column2 like @column2 OR nullif(@column2, '') is null)'
**/
我不喜欢动态查询(我只是懒惰)。但是,为此我一直在尝试动态查询和 sp_executesql。我不确定是否可以使用 56 个参数为此创建动态查询,其中许多参数将为空(前端未提供任何内容)。我只是想知道在不使用动态查询的情况下是否有更好的方法。
【问题讨论】:
标签: tsql stored-procedures null optional-parameters