Home  >  Article  >  Database  >  sqlserver中根据字符分割字符串的最好的写法分享

sqlserver中根据字符分割字符串的最好的写法分享

WBOY
WBOYOriginal
2016-06-07 18:05:411079browse

因数据库中保存的是以,号分隔的数据,需要在界面上以表格的方式显示出来。特想出以下方法

知识点:
1、拼接SQL
2、UNION ALL
3、EXEC
其代码如下:
代码如下:
--测试示例
declare @sql varchar(2000),@tsql nvarchar(max),@split varchar(100)
set @sql='A,B,C,D,E' --保存的字符
set @split=','--分隔符
select @tsql='select '''+replace(@sql,@split,''' union all select ''')+''''
exec(@tsql)


显示结果:
----
A

C
D
E
(5 行受影响)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn