
[英]How to check a comma delimited integer values by “IF” condition T-SQL?
[英]T-Sql condition check
我有一个表,其中有一个列称为allocated_to
。 如果该列中有一个值,则表示该行的状态已assigned
否则unassigned
。
从我的搜索框中,我发送1
表示已assigned
, 0
表示未分配。 另外,在名为SignOff (type: int)
列上,我还有两个类似的pending
和closed
检查SignOff (type: int)
。
现在共有9条搜索条件
1. Pending
2.Closed
3. Unassigned
4. Assigned
5. Pending + Unassigned
6. Pending + Assigned
7. Closed + Unassigned
8. Closed + Assigned
9. For all records irrespective of any statuses.
因此,如何为查询添加条件。 实际上,它在SP和SP中的更改已经启动并正在运行。 因此,我无法通过使其动态或任何方式对查询进行重大更改。
我可以在这里给您一个示例,我的查询如下:
If Some_Condition
begin
Select x,y,zfrom T1 join T2 on t1.a=t2.b
Where IsNull(SignOff,0)=@ParamForPendingAndClosed
end
现在我想将我上面的9个检查添加到这里,有什么帮助吗?
请注意:
我不能进行大量改动,因为我需要在每个if-else条件下进行更改。 查询是否有将近4-5的查询,具体取决于其标题条件,请不要建议我使用动态过程。 除此之外,欢迎。
您可以添加几个可选参数,这些参数使您可以指定结果应包括待处理/已关闭结果还是已分配/未分配结果。 通过这种方式,您可以维护一种灵活的检索结果的方式。
查看此SO Answer ,以了解在SQL中使用可选参数的概述。
因此,如果我正确理解,您可以独立地基于两个条件进行筛选。 选项1是“待定”,“关闭”或“ dont-filter”,选项3是“已分配”,“未分配”和“ dont-filter”。 “ dont-filter”表示在项目筛选中不使用该标准,即返回的项目可以对该参数具有任何值。
结合这两个过滤器,您可以获得3 X 3 = 9种可能的情况。
我要做的是使用发送到该过程的参数的值来按照我的需要塑造查询,方法如下:
create procedure getItems
@Status int, -- 0 - don't filter, 1 - pending, 2 - closed
@Assignment int -- 0 - don't filter, 1 - assigned, 2 - not assigned
as
begin
select * from Items
where ((@Status = 0)
and ((@Assignment = 0) -- no filter at all
or (@Assignment = 1 and allocated_to is not null)
or (@Assignment = 2 and allocated_to is null)))
or ((@Status = 1 and pending is not null)
and ((@Assignment = 0)
or (@Assignment = 1 and allocated_to is not null)
or (@Assignment = 2 and allocated_to is null)))
or ((@Status = 2 and closed is not null)
and ((@Assignment = 0)
or (@Assignment = 1 and allocated_to is not null)
or (@Assignment = 2 and allocated_to is null)))
end
SQL Server非常聪明,可以使用参数嗅探来优化实际查询运行,因此,基本上,如果您发送0, 0
作为参数,则查询将执行为
select * from Items
如果发送1, 2
查询将执行为
select * from Items
where pending is not null
and allocated_to is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.