[英]SQL: Split comma separated string list with a query?
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.我需要拆分PaymentCond
列,并且很乐意使用简单的 sql 查询来做到这一点,因为我不知道如何使用函数,并且希望保持简单。
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?有没有办法将所有内容从PaymentConditions
为COND_1
、 COND_2
、 COND_3
等等?
Thanks in advance.提前致谢。
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
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
There is a new table-valued function in SQL Server STRING_SPLIT : 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但请注意它在您的数据库中的可用性: STRING_SPLIT
函数仅在兼容级别 130 下可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.