0
我需要使用分隔符分隔列中的一列值,下面是表結構。使用SQL Server按分隔符分隔字符串
create table #a
(
id int,
timeline varchar(100)
)
insert into #a
values (1, 'Semi Annual Q2 (May/June/July) & Q4 (Nov/Dec/Jan)'),
(2, 'Semi Annual Q1 (Feb/Mar/Apr) & Q3 (Aug/Sep/Oct)'),
(3, 'Annual Q3 (Aug/Sep/Oct)'),
(4, 'Annual Q2 (May/June/July)'),
(5, 'Annual Q4 (Nov/Dec/Jan)'),
(6, 'Semi Annual Q1 (Jan/Feb/Mar) & Q3 (July/Aug/Sep)')
select * from #a
輸出我想通過「/」分隔符分割時間表值並單獨列單獨的一個月,整整一個月應該在序列,它看起來像下面的示例。
ID M1 M2 M3 M4 M5 M6
---------------------------------------
1 May June July Nov Dec Jan
2 Feb Mar Apr Aug Sep Oct
3 Aug Sep Oct NULL NULL NULL
4 May June July NULL NULL NULL
5 Nov Dec Jan NULL NULL NULL
6 Jan Feb Mar July Aug Sep
到目前爲止,我已經試過這樣:
select
timeline,
substring((substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline) - 1)), 1, charindex('/', substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline) - 1)) - 1) as M1,
replace(replace(right(substring(substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline)), 1, charindex(')', substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline)))), charindex('/', reverse(substring(substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline)), 1, charindex(')', substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline))))), 4)), '/', ''), ')', '') as M3
from
#a;
這不是一個代碼,同時也過於繁瑣。請幫助,如果你有這種方法有效的方法。
Jeff Moden的DelimitedSplit8K函數應該可以做到這一點...你可以在這裏找到它... http://www.sqlservercentral.com/articles/Tally+Table/72993/ –
I al所以推薦Jeff的分配器。但更重要的是,我建議結束存儲分隔數據的做法。它違反了1NF並導致很多痛苦。 –
[如何將逗號分隔值拆分爲列]可能的重複(https://stackoverflow.com/questions/10581772/how-to-split-a-comma-separated-value-to-columns) –