2017-04-13 1718 views
3

这里是我的表结构:SQL:用查询拆分逗号分隔的字符串列表?

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 

是有办法的一切分裂从PaymentConditionsCOND_1COND_2COND_3等等?

在此先感谢。

+0

看看http://stackoverflow.com/questions/5928599/equivalent-of-explode-to -work-with-strings-in-mysql –

+0

应该是...... – Chanukya

+0

你可以使用'STRING_SPLIT' https://docs.microsoft.com/en-us/sql/t-sql/functions/string- split-transact-sql – Jodrell

回答

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 @[email protected]+5 
END 
Select SchoolYear from #TempFY 
+1

如果你在这个awnser上添加注释将会很好。 –

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 

输出

id token 
1 ZBE1 
1 AP1 
1 LST2 
1 CC1 
2 VB3 
2 CC1 
2 ZBE1 
0

有在SQL Server新功能STRING_SPLIT

DECLARE @tags NVARCHAR(400) = 'aaaa,bbb,,cc,d' 
SELECT * 
FROM STRING_SPLIT(@tags, ',') 

您将获得:

Result

但要注意其可用性在您的DB:该STRING_SPLIT功能只有在兼容级别可用130