我有 3 种过滤方式:
- 按名字
- 按列表
- 并显示所有
我正在使用 ASP.NET 3.5 和 SQL Server 2008。使用 ADO.NET 和存储过程。
我将列表作为表值参数传递(但我正在使用表变量进行测试)并将名称作为 nvarchar 传递。我将“全部显示”为 ISNULL(@var, column) = column。显然,我查询这个的方式没有利用短路或我对 WHERE 子句如何工作的理解缺乏。发生的情况是,如果我创建 @var = 'some string' 并将 null 插入到表变量中,那么它会正确过滤。如果我让@var = null 并将“一些字符串”插入到表变量中,那么我会得到每条记录,我应该得到“一些字符串”。
编码:
declare @resp1 nvarchar(32)
set @resp1 = null
declare @usersTable table
(responsible nvarchar(32))
--insert into @usersTable (responsible) values (null)
insert into @usersTable (responsible) values ('ssimpson')
insert into @usersTable (responsible) values ('kwilcox')
select uT.responsible, jsq.jobnumber, jsq.qid, aq.question, aq.section, aq.seq, answers.*
from answers
inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid
inner join apqp_questions as aq on jsq.qid = aq.qid
left join @usersTable as uT on uT.responsible = answers.responsible
where answers.taskAction = 1 and (uT.responsible is not null or ISNULL(@resp1, Answers.responsible) = Answers.responsible)
order by aq.section, jsq.jobnumber, answers.priority, aq.seq
这就是我想出的。虽然很丑……
declare @resp1 nvarchar(32)
set @resp1 = 'rrox'
declare @filterPick int
declare @usersTable table
(responsible nvarchar(32))
insert into @usersTable (responsible) values (null)
--insert into @usersTable (responsible) values ('ssimpson')
--insert into @usersTable (responsible) values ('kwilcox')
if @resp1 is null
begin
set @filterPick = 2
end
else
begin
set @filterPick = 1
end
select uT.responsible, jsq.jobnumber, jsq.qid, aq.question, aq.section, aq.seq, answers.*
from answers
inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid
inner join apqp_questions as aq on jsq.qid = aq.qid
left join @usersTable as uT on uT.responsible = answers.responsible
where answers.taskAction = 1 and
(case
when uT.responsible is not null then 2
when ISNULL(@resp1, Answers.responsible) = Answers.responsible then 1
end = @filterPick )
order by aq.section, jsq.jobnumber, answers.priority, aq.seq
好的。我想我明白了。我删除了@resp1,因为它不是必需的,我只是使用表值参数@usersTable(但这里我使用表变量进行测试)。我添加了一个标志@filterPick,因此我可以只显示@usersTable 或answers.taskAction = 1 的每条记录中的值。
编码:
declare @filterPick bit
declare @usersTable table
(responsible nvarchar(32))
insert into @usersTable (responsible) values (null)
--insert into @usersTable (responsible) values ('ssimpson')
--insert into @usersTable (responsible) values ('kwilcox')
if exists (select * from @usersTable where responsible is not null)
begin
set @filterPick = 1
end
else
begin
set @filterPick = 0
end
select *
from answers
inner join jobno_specific_questions as jsq on answers.jqid = jsq.jqid
inner join apqp_questions as aq on jsq.qid = aq.qid
left join @usersTable as uT on answers.responsible = uT.responsible
where answers.taskAction = 1 and (uT.responsible is not null or (isnull(uT.responsible, answers.responsible) = answers.responsible and @filterPick = 0))
order by aq.section, jsq.jobnumber, answers.priority, aq.seq