问题
Here is my table structure:
id PaymentCond
1 ZBE1, AP1, LST2, CC1
2 VB3, CC1, ZBE1
I need to split the column PaymentCond
, and would love to do that with a simple sql query since I have no clue how to use functions and would love to keep it all simple.
Here is what I already found:
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'
But this only outputs
id COND_1 COND_2
1 ZBE1 AP1, LST2, CC1
Is there a way to split everything from PaymentConditions
to COND_1
, COND_2
, COND_3
and so on?
Thanks in advance.
回答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:
first create function to split values
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
output
id token
1 ZBE1
1 AP1
1 LST2
1 CC1
2 VB3
2 CC1
2 ZBE1
回答3:
there is new function in SQL Server STRING_SPLIT:
DECLARE @tags NVARCHAR(400) = 'aaaa,bbb,,cc,d'
SELECT *
FROM STRING_SPLIT(@tags, ',')
You will get:
But be careful its availability in your DB: The STRING_SPLIT
function is available only under compatibility level 130
来源:https://stackoverflow.com/questions/43386709/sql-split-comma-separated-string-list-with-a-query