日期:2014-05-18 浏览次数:20446 次
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',null insert into tb select 4,'2,3','true',null go declare @sql varchar(2000) select @sql='select * from tb where id in('+bid+')' from tb exec(@sql) /* ID BID ISMust Result ----------- -------------------- ---------- ---------- 2 1 true NO 3 1,2 true NULL (2 行受影响) */ go drop table tb
------解决方案--------------------
---------------------------- -- 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 all select 2,'1','true','NO' union all select 3,'1,2','true',null union all select 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 NO 3 1,2 true NULL (2 行受影响) */