如何在 SQL Server 2008 或更高版本中没有拆分功能的单一选择查询中由某些字符分隔的数据从单行获取唯一的多行。
示例:
ID Data Name
1 '2014-01-01,2014-01-02,2014-01-03,2014-01-04' 'A1'
2 '2014-01-01,2014-01-02' 'B1'
3 '2014-01-03,2014-01-05,2014-01-06,2014-01-07' 'A1'
ID Data Name
1 '2014-01-01' 'A1'
1 '2014-01-02' 'A1'
1 '2014-01-03' 'A1'
1 '2014-01-04' 'A1'
3 '2014-01-05' 'A1'
3 '2014-01-06' 'A1'
3 '2014-01-07' 'A1'
2 '2014-01-01' 'B1'
2 '2014-01-02' 'B1'
答案 0 :(得分:0)
查看有关字符串拆分的SQL Sentry文章。如果讨论不同的技术,每个技术的速度和任何陷阱。
http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings
拆分字符串并获取不同的值。
下面的代码使用xml spliter。
-- Just playing
use tempdb;
go
-- drop the table
if object_id('results') > 0
drop table results
go
-- create the table
create table results
(
id int,
data varchar(128),
name varchar(2)
);
go
-- add data
insert into results values
(1,'2014-01-01,2014-01-02,2014-01-03,2014-01-04','A1'),
(2,'2014-01-01,2014-01-02','B1'),
(3,'2014-01-03,2014-01-05,2014-01-06,2014-01-07','A1');
go
-- Just the data
select * from results
-- Split the data
select distinct r.id, r.name, s.item
from results r
cross apply dbo.SplitStrings_XML(data, ',') s