日期:2014-05-18 浏览次数:20777 次
--> 测试数据:[ta] if object_id('[ta]') is not null drop table [ta] go create table [ta]([id] int,[name] varchar(4)) insert [ta] select 1,'张三' union all select 2,'李四' union all select 3,'王五' union all select 4,'赵六' --> 测试数据:[tb] if object_id('[tb]') is not null drop table [tb] go create table [tb]([id] int,[name] varchar(5)) insert [tb] select 1,'1,2,4' union all select 2,'2,3' --------------开始查询-------------------------- go create function f_hb(@id varchar(10)) returns varchar(1000) as begin declare @str varchar(1000) set @str='' select @str=@str+','+[name] from [ta] where charindex(','+cast(id as varchar)+',',','+@id+',')>0 return stuff(@str,1,1,'') end go select id,name=dbo.f_hb([name]) from [tb] --drop function f_hb --drop table ta,tb /*
------解决方案--------------------
--> 测试数据:[ta] if object_id('[ta]') is not null drop table [ta] go create table [ta]([id] int,[name] varchar(4)) insert [ta] select 1,'张三' union all select 2,'李四' union all select 3,'王五' union all select 4,'赵六' --> 测试数据:[tb] if object_id('[tb]') is not null drop table [tb] go create table [tb]([id] int,[name] nvarchar(5),tab1 varchar(20)) insert [tb] select 1,N'作者','1,2,4' union all select 2,N'文章','2,3' select b.ID, b.name, stuff((select ','+[name] from ta a where CHARINDEX(','+ltrim(a.id)+',',','+b.tab1+',')>0 for XML path('')),1,1,'') from tb b
------解决方案--------------------