求一条SQL语句!!
表1:
ID Name
1 a
2 b
3 c
4 d
如何使用字符串“2,3,4,5” 查询到结果“b,c,d”
[解决办法]
declare @s varchar(8000),@ids varchar(200)
set @ids='2,3,4,5'
set @s=''
;with cte(ID,Name) as
(
select 1,'a'
union all select 2,'b'
union all select 3,'c'
union all select 4,'d'
)
select @s=@s+Name+','
from cte
where CHARINDEX(','+cast(id as varchar)+',',','+@ids+',')>0
print left(@s,len(@s)-1)
/*
b,c,d
*/
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-08 14:57:27
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
--Jun 10 2013 20:09:10
--Copyright (c) Microsoft Corporation
--Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] int,[Name] varchar(1))
insert [huang]
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d'
--------------开始查询--------------------------
declare @s varchar(8000),@ids varchar(200)
set @ids='2,3,4,5'
set @s=''
select @s=@s+Name+','
from [huang]
where CHARINDEX(','+cast(id as varchar)+',',','+@ids+',')>0
select left(@s,len(@s)-1)
----------------结果----------------------------
/*
----------------------------------------------------------------------------------------------------------------
b,c,d
*/