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

sql in的使用,该怎么处理

2012-04-10 
sql in的使用表结构为IDBIDISMustResult10trueOK21trueNO31,2truenull42,3truenull以 ID 为 4 的记录为例,

sql in的使用
表结构 为 

ID BID ISMust Result

1 0 true OK

2 1 true NO

3 1,2 true null

4 2,3 true null

以 ID 为 4 的记录为例,需要查询出 ID 为 2,3的Result 

BID 的数据类型为nvarchar

使用 关键字In 无法进行查询!
在sql 中该如何查询!使用sql 语句,不是C#的代码? 








[解决办法]

SQL code
create table tb(ID int,BID varchar(20),ISMust varchar(10),Result varchar(10))insert into tb select 1,'0','true','OK'insert into tb select 2,'1','true','NO'insert into tb select 3,'1,2','true',nullinsert into tb select 4,'2,3','true',nullgodeclare @sql varchar(2000)select @sql='select * from tb where id in('+bid+')' from tbexec(@sql)/*ID          BID                  ISMust     Result----------- -------------------- ---------- ----------2           1                    true       NO3           1,2                  true       NULL(2 行受影响)*/godrop table tb
[解决办法]
SQL code
------------------------------ Author  :fredrickhu(小F,向高手学习)-- Date    :2011-09-21 09:58:52-- Verstion:--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) --    Apr 22 2011 11:57:00 --    Copyright (c) Microsoft Corporation--    Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)--------------------------------> 测试数据:[tb]if object_id('[tb]') is not null drop table [tb]go create table [tb]([ID] int,[BID] varchar(3),[ISMust] varchar(4),[Result] varchar(2))insert [tb]select 1,'0','true','OK' union allselect 2,'1','true','NO' union allselect 3,'1,2','true',null union allselect 4,'2,3','true',null--------------开始查询--------------------------select distinct a.* from tb a,tb b where CHARINDEX(','+ltrim(b.ID)+',',','+a.BID+',')>0  and a.ID<>4----------------结果----------------------------/* ID          BID  ISMust Result----------- ---- ------ ------2           1    true   NO3           1,2  true   NULL(2 行受影响)*/ 

热点排行
Bad Request.