问题:SQL Server 2005中如何利用xml拆分字符串序列? 解答:下文中介绍的方法比替换为select union all方法更为见效,并且不用考虑因为字符串过长而导致动态sql语句过长。 代码如下: DECLARE @str varchar(1000) DECLARE @idoc int; DECLARE @doc xml; set @str='1¦3¦4¦25' set @doc=cast('<Root> <item><ID>'+replace(@str,'¦',' </ID></item><item><ID>')+'</ID></item></Root>' as xml) EXEC sp_xml_preparedocument @Idoc OUTPUT, @doc SELECT * FROM OPENXML (@Idoc, '/Root/item',2) WITH ( [ID] varchar(10) ) /**//* ID ----------- 1 3 4 25*/
解答:下文中介绍的方法比替换为select union all方法更为见效,并且不用考虑因为字符串过长而导致动态sql语句过长。
代码如下:
DECLARE @str varchar(1000) DECLARE @idoc int; DECLARE @doc xml; set @str='1¦3¦4¦25' set @doc=cast('<Root> <item><ID>'+replace(@str,'¦',' </ID></item><item><ID>')+'</ID></item></Root>' as xml) EXEC sp_xml_preparedocument @Idoc OUTPUT, @doc SELECT * FROM OPENXML (@Idoc, '/Root/item',2) WITH ( [ID] varchar(10) ) /**//* ID ----------- 1 3 4 25*/