首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

条件的组合查询解决方案

2012-05-28 
条件的组合查询可以通过组合条件来进行查询一组数据吗?比如..一个表id typeId projectId111221331我这里传

条件的组合查询
可以通过组合条件来进行查询一组数据吗?
比如..
一个表
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 allselect 2,2,1 union allselect 3,3,1declare @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 Resultfrom master..spt_values aleft join [test] bon a.number=b.idwhere number between LEFT(@str,1) and RIGHT(@str,1) and type='P'/*id    typeId    projectId    Result1    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 

热点排行
Bad Request.