日期:2014-05-17 浏览次数:20897 次
create table #test ( id int not null, name nvarchar(100) null ) insert into #test values(1,'张三') insert into #test values(2,'李四') insert into #test values(3,'王五') declare @a nvarchar(50) set @a='1,1,2,3' select a.id,a.name from #test a left join f_split_dh(@a) b on a.id=b.a drop table #test --标值函数f_split_dh Create function [dbo].[f_split_dh](@SourceSql varchar(8000)) returns @temp table(a varchar(100)) as begin declare @i int set @SourceSql=rtrim(ltrim(@SourceSql)) set @i=charindex(',',@SourceSql) while @i>=1 begin insert @temp values(left(@SourceSql,@i-1)) set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i) set @i=charindex(',',@SourceSql) end if @SourceSql<>',' insert @temp values(@SourceSql) return end GO --1 张三 --1 张三 --2 李四 --3 王五
------解决方案--------------------
create table t1 ( id int, name varchar(10) ) insert into t1 values (1,'张三') insert into t1 values (2,'李四') insert into t1 values (3,'王五') select * from t1 declare @str varchar(4000)='1,1,2,3' create table #tt ( id int ) set @str=REPLACE(@str,',',' union all select ') set @str=' insert into #tt select '+@str print @str exec (@str) select t1.name from #tt inner join t1 on #tt.id=t1.id drop table #tt -------------------- name 张三 张三 李四 王五