SQL Server拆分字符串的3常用种方法

以下的文章主要是介绍的是SQL Server拆分字符串的3常用种方法,我前两天在相关网站看见SQL Server拆分字符串的3常用种方法的资料,觉得挺好,就拿出来供大家分享,望会给大家带来一些帮助在此方面。

 

  1. use tempdb  
  2. use tempdb  
  3. go  

 

测试数据

 

  1. declare @s varchar(1000)  
  2. set @s='ak47,mp5,1,23' 

 

要求输出结果

 

  1. S  
  2. ak47  
  3. mp5  
  4. 1  
  5. 23  
  6.  

SQL Server拆分字符串的3种方法对比:

SQL Server拆分字符串1.[朴实]动态Exec方法:

 

  1. declare @s1 varchar(1000)  
  2. set @s1=right(replace(','+@s,',',''' as S union select '''),len(replace(','+@s,',',''' as S union select '''))-12)+''''  
  3. exec(@s1)  
  4.  

 

SQL Server拆分字符串2.[变通]表交叉方法:

 

  1. select replace(reverse((left(s,charindex(',',s)))),',','') as S from(  
  2. select r,reverse(left(@s,r))+',' as s  
  3. from(  
  4. select (select count(*) from sysobjects where name<=t.name ) as r  
  5. from sysobjects t  
  6. )a where r<=len(@s)  
  7. and left(@s+',',r+1) like '%,'  
  8. )t order by r  

 

SQL Server拆分字符串3.[高级]XML方法:

 

  1. DECLARE @idoc int;  
  2. DECLARE @doc xml;  
  3. set @doc=cast('<Root><item><S>'+replace(@s,',','</S></item><item><S>')+'</S></item></Root>' as xml)  
  4. EXEC sp_xml_preparedocument @Idoc OUTPUT, @doc  
  5. SELECT * FROM OPENXML (@Idoc, '/Root/item',2)  
  6. WITH (  
  7. [S] varchar(10)  
  8. )  
  9.  

 

以上的相关内容就是对SQL Server拆分字符串的三种方法的介绍,望你能有所收获。

【编辑推荐】

  1. SQL Server 2005 synonyms的优缺点有哪些?
  2. SQL Server快照功能以及其查询操作
  3. SQL Server行转列的什么情况下被用?
  4. SQL Server排序遇到NULL,不怕不帕!
  5. SQL Server 2005两种快照隔离机制的不同之处

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/285471.html<

(0)
运维的头像运维
上一篇2025-05-14 21:55
下一篇 2025-05-14 21:56

相关推荐

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注