日期:2014-05-18 浏览次数:20526 次
create table tb(docid int,doctitle nvarchar(10)) insert into tb select 1,'hello' insert into tb select 2,'nihao' insert into tb select 3,'你好' insert into tb select 120,'你好aaaa' declare @str varchar(2000)='1,3,3,120,2,1' set @str='select a.* from tb a,(select '+REPLACE(@str,',',' as id union all select ') +') b where a.docid=b.id' print @str exec (@str) /* docid doctitle ----------- ---------- 1 hello 3 你好 3 你好 120 你好aaaa 2 nihao 1 hello
------解决方案--------------------
use tempdb go --测试数据 declare @s varchar(1000) set @s='ak47,mp5,1,23' /*要求输出结果 S ---- ak47 mp5 1 23 */ --3种方法对比: --1.[朴实]动态Exec方法: declare @s1 varchar(1000) set @s1=right(replace(','+@s,',',''' as S union select '''),len(replace(','+@s,',',''' as S union select '''))-12)+'''' exec(@s1) --2.[变通]表交叉方法: select replace(reverse((left(s,charindex(',',s)))),',','') as S from( select r,reverse(left(@s,r))+',' as s from( select (select count(*) from sysobjects where name<=t.name ) as r from sysobjects t )a where r<=len(@s) and left(@s+',',r+1) like '%,' )t order by r --3.[高级]XML方法: DECLARE @idoc int; DECLARE @doc xml; set @doc=cast('<Root><item><S>'+replace(@s,',','</S></item><item><S>')+'</S></item></Root>' as xml) EXEC sp_xml_preparedocument @Idoc OUTPUT, @doc SELECT * FROM OPENXML (@Idoc, '/Root/item',2) WITH ( [S] varchar(10) )