create table policies
(
policyno varchar(15)
);
insert into policies values ('500'),('501'),('502'),('503');
Declare @PolicyNos varchar(1500) = '500|503';
SELECT * FROM policies
WHERE policyno = ALL(SELECT item from dbo.fnSplit(@PolicyNos,'|'));
用户将从前端输入多个策略,并发送多个应用程序 策略管道分隔为@PolicyNos变量。
我正在使用此处提供的拆分功能https://stackoverflow.com/a/337752/435559来检查@PolicyNos中的所有策略是否必须存在然后如果存在任何一个,则返回true但不返回另一个然后返回false。
我试过IN和EXISTS但他们在内部进行OR操作但是我想要并且每个策略都存在然后返回true,否则为false。
编辑 - 添加了我尝试的存在代码
SELECT * FROM policies
WHERE policyno IN (SELECT item from dbo.fnSplit(@PolicyNos,'|'));
SELECT * FROM policies
WHERE exists (SELECT item from dbo.fnSplit(@PolicyNos,'|') where item = policies.policyno);
答案 0 :(得分:1)
您可以使用条件聚合执行此操作:
WITH vals(val) as (
SELECT item
FROM dbo.fnSplit(@PolicyNos,'|')
)
SELECT (CASE WHEN COUNT(DISTINCT v.val) = COUNT(DISTINCT p.policyno) THEN 'true'
ELSE 'false'
END)
FROM vals v left join
policies p
ON v.val = p.policyno
答案 1 :(得分:0)
我可能不太了解您的问题,但您可以找到无效的政策代码
SELECT item AS invalidPolicy
FROM dbo.fnSplit(@PolicyNos,'|')
WHERE NOT EXISTS (
SELECT *
FROM policies
WHERE item = policies.policyno
)
如果您需要条件
IF EXISTS (
SELECT item AS invalidPolicy
FROM dbo.fnSplit(@PolicyNos,'|')
WHERE NOT EXISTS (
SELECT *
FROM policies
WHERE item = policies.policyno
)
) BEGIN
.....
END
ELSE BEGIN
......
END