2017-04-13 1751 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