这是我的表结构:
id PaymentCond
1 ZBE1, AP1, LST2, CC1
2 VB3, CC1, ZBE1
我需要拆分列PaymentCond
,并希望通过一个简单的SQL查询来做到这一点,因为我不知道如何使用函数,并希望保持简单。
以下是我已经找到的内容:
SELECT id,
Substring(PaymentConditions, 1, Charindex(',', PaymentConditions)-1) as COND_1,
Substring(PaymentConditions, Charindex(',', PaymentConditions)+1, LEN(ANGEBOT.STDTXT)) as COND_2
from Payment
WHERE id = '1'
但这只是输出
id COND_1 COND_2
1 ZBE1 AP1, LST2, CC1
有没有办法将所有内容从PaymentConditions
拆分为COND_1
,COND_2
,COND_3
等等?
提前致谢。
答案 0 :(得分:2)
首先创建分割值的函数
create function [dbo].[udf_splitstring] (@tokens varchar(max),
@delimiter varchar(5))
returns @split table (
token varchar(200) not null )
as
begin
declare @list xml
select @list = cast('<a>'
+ replace(@tokens, @delimiter, '</a><a>')
+ '</a>' as xml)
insert into @split
(token)
select ltrim(t.value('.', 'varchar(200)')) as data
from @list.nodes('/a') as x(t)
return
end
CREATE TABLE #Table1
([id] int, [PaymentCond] varchar(20))
;
INSERT INTO #Table1
([id], [PaymentCond])
VALUES
(1, 'ZBE1, AP1, LST2, CC1'),
(2, 'VB3, CC1, ZBE1')
;
select id, token FROM #Table1 as t1
CROSS APPLY [dbo].UDF_SPLITSTRING([PaymentCond],',') as t2
输出
id token
1 ZBE1
1 AP1
1 LST2
1 CC1
2 VB3
2 CC1
2 ZBE1
答案 1 :(得分:1)
declare @SchoolYearList nvarchar(max)='2014,2015,2016'
declare @start int=1
declare @length int=4
create table #TempFY(SchoolYear int)
while @start<len(@SchoolYearList)
BEGIN
Insert into #TempFY
select SUBSTRING(@SchoolYearList,@start,@length)
set @start=@start+5
END
Select SchoolYear from #TempFY
答案 2 :(得分:0)