摘要:
下文讲述在 sqlserver 对逗号分隔的字符串转换为数据表的另类方法实现, 如下所示:
实验环境: sql server 2008 R2
实现思路:
将组合字符串中的逗号替换为 "'as n union all select' ", 然后将替换后的字符串加上 select 和 前后加上单引号 是其成为可执行 sql 脚本,
最后运行替换后的字符串, 就可以得到一张数据表, 如下所示:
- declare @maomao365 varchar(1000)
- set @maomao365 ='sqlserver,blog,other';
--- 将逗号替换为'as n union all select'
- set @maomao365 = REPLACE(@maomao365,',',
- '''as n union all select'''
- );
--- 在字符串前面加上 select 和单引号 , 后面也加上单引号
- set @maomao365 ='select'''+ @maomao365 + '''';
- print @maomao365
- exec (@maomao365)
来源: http://www.bubuko.com/infodetail-3300907.html