create table a
(
id int,
List varchar(100)
)
insert into a
select 1,'1,2,3,4,5'
union select 2,'13,16,28,44'
union select 3,'6,7,11,18'
create table b
(
id int,
Name varchar(100)
)
insert into b
select 1,'A'
union select 2,'B'
union select 3,'C'
union select 13,'D'
union select 28,'E'
union select 44,'F'
union select 49,'G'
select * from b where id in(select List from a where id<3)
提示:在将 varchar 值 '1,2,3,4,5' 转换成数据类型 int 时失败。
这样的查询语句应该怎样写才能查询出
1 A
2 B
3 C
13 D
28 E
44 F
------解决思路----------------------
用动态SQL实现,
declare @tsql varchar(6000)
select @tsql=isnull(@tsql+',','')+List
from a
where id<3
select @tsql='select * from b where id in('+@tsql+')'
exec(@tsql)
/*
id Name
----------- --------------
1 A
2 B
3 C
13 D
28 E
44 F
(6 行受影响)
*/
------解决思路----------------------
-- 可以考虑使用 like
select b.* from b , a
where ',' + a.List + ',' like '%,' + cast(b.id as varchar(10)) + ',%'
go
id Name
----------- -------------
1 A
2 B
3 C
13 D
28 E
44 F
(6 行受影响)