日期:2014-05-18  浏览次数:20460 次

条件的组合查询
可以通过组合条件来进行查询一组数据吗?
比如..
一个表
id typeId projectId
1 1 1
2 2 1
3 3 1

我这里传入一个ProjectId=1
和一个数组的TypeId={1,2,3,4}来一次判断
proId和TypeId组合的数据是否存在?
比如
id typeId projectId Result
1 1 1 存在
2 2 1 存在
3 3 1 存在
4 4 1 不存在

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([id] int,[typeId] int,[projectId] int)
insert [test]
select 1,1,1 union all
select 2,2,1 union all
select 3,3,1

declare @str varchar(20)
set @str='1,2,3,4'

select number as [id],ISNULL([typeId],number) [typeId],
ISNULL([projectId],1) [projectId],case when CHARINDEX(ltrim([id]),@str)>0 then '存在'
else '不存在' end as Result
from master..spt_values a
left join [test] b
on a.number=b.id
where number between LEFT(@str,1) and RIGHT(@str,1)
 and type='P'
/*
id    typeId    projectId    Result
1    1    1    存在
2    2    1    存在
3    3    1    存在
4    4    1    不存在 
*/

------解决方案--------------------
SQL code

select *,cz=case 
    when projectid=1 and typeid in(1,2,3,4) then '存在'
    else '不存在'
    end
 from test