0

我在Filter类中有4个以下的属性。我将解析4个以下属性到StoredProcedure并获取过滤结果。如何创建SQL运算符组合像ALL IN,NOT ALL

​​

我的存储过程将有四个参数,如下所示。 例如:

@ * MustHaveAll *条件= “1,2”

@ * MustNotHaveAll *条件= “3,4”

@ * MustHaveAtLeastOne *条件=“ 5,6,7,8-“

@ * MustNotHaveAtLeastOne *条件= ”9,10“

我正在使用一个UDF,它返回一个带有Ids列的表。

我的问题:

基本上我可以使用SQL“IN”运算符查找谁拥有至少一个条件的患者(即:@MustHaveAtLeastOneCondition)和“NOT IN”运算符组合过滤@MustNotHaveAnyConditions。

是否有任何SQL运算符(或esay方式)来过滤MustHaveAllConditions,MustNotHaveAllConditions参数?

回答

1
-- Patients 
declare @Patient table (PatientID int) 

-- Conditions per patient 
declare @PatientCondition table (PatientID int, ConditionID int) 

-- Conditions table generated from param string 
declare @Condition table (ConditionID int) 

-- Test data 
insert into @Patient 
select 1 union all 
select 2 union all 
select 3 

insert into @PatientCondition 
select 1, 1 union all 
select 1, 2 union all 
select 1, 3 union all 
select 2, 1 union all 
select 3, 3 

insert into @Condition 
select 1 union all 
select 2 


-- MustHaveAll 
select * 
from @Patient as P 
where P.PatientID in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     inner join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    group by PC.PatientID 
    having count(PC.ConditionID) = (select count(ConditionID) from @Condition) 
) 

--MustNotHaveAll 
select * 
from @Patient as P 
where P.PatientID not in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     inner join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    group by PC.PatientID 
    having count(PC.ConditionID) = (select count(ConditionID) from @Condition) 
) 

-- MustHaveAtLeastOne 
select * 
from @Patient as P 
where P.PatientID in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     left outer join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    where C.ConditionID is not null 
) 

--MustNotHaveAtLeastOne 
select * 
from @Patient as P 
where P.PatientID not in 
    (
    select PC.PatientID 
    from @PatientCondition as PC 
     left outer join @Condition as C 
     on PC.ConditionID = C.ConditionID 
    where C.ConditionID is not null 
) 
+0

这很好。如果我想在一个SQL查询中合并这四个条件以获得患者的最终名单,您能告诉我最有效的方法吗? – CharithJ 2011-05-16 06:08:26

+1

@CharithJ - 您可以将不同查询中的where子句添加到一个查询中,并用'和'分开。 (...)中的PatientID以及(...)和...中的PatientID等。 – 2011-05-16 06:17:29

0

真的不是一个简单的方法来做你所描述的。我会做的是可能把你的字符串和分裂成一个表变量,然后使用右,左和内部联合的组合来从我的输出中删除另一个表变量的结果。