我正在寻找帮助拆分在sql函数/语句中使用多个分隔符的字段。我已经按照已经列出HERE
的几个例子这里使用单个分隔符可以很好地工作。但是,我需要拆分基于以下内容的字段。它的格式是qty x itemno description,qty x itemno description等。因此我需要拆分第一个'x'第二个空格''和最后一个逗号的语句。我想我可以基于a分割它正则表达式声明,但不确定如何去做..
有人可以帮忙吗?
OnSameLine = substring( ( SELECT ', ' +
coalesce (CAST(CNT.qty AS varchar(1000)), '') +
' x ' + '['+ coalesce (CNT.Itemno,'') + ']' +
' ' + coalesce (STK.Desc#1,'')
格式我需要..
PK qty itemno description
PK qty itemno description
等。
答案 0 :(得分:1)
试试这个:
基于here
的文章;with T(id, Cols) as
(
select 1, '10 x 1234 description1,11 x 456 description2'
UNION ALL
select 2, '40 x 123478 description3,51 x 45678 description4'
),
--first split all comma separated into different rows
CTE2 AS
(
SELECT id,
CAST(N'<H><r>' + replace(Replace(Vals.a.value('.', 'NVARCHAR(50)'),
' ','|'), '|', '</r><r>') + '</r></H>' as XML) Cols
FROM
(
SELECT *,CAST (N'<H><r>' + Replace(cols,',','</r><r>') +
'</r></H>' AS XML) AS [vals]
FROM T) d
CROSS APPLY d.[vals].nodes('/H/r') Vals(a)
)
-- split all ' ' demilited values now
SELECT distinct id, Vals.a.value('(/H/r)[1]', 'VARCHAR(100)') AS Qty,
Vals.a.value('(/H/r)[2]', 'VARCHAR(100)') AS X,
Vals.a.value('(/H/r)[3]', 'VARCHAR(100)') AS ItemNo,
Vals.a.value('(/H/r)[4]', 'VARCHAR(100)') AS Description
FROM
(
SELECT *
FROM CTE2) d
CROSS APPLY d.[cols].nodes('/H/r') Vals(a)
答案 1 :(得分:0)
如果你只是想分开,并交换数量和PK,试试这个;
DECLARE @S VARCHAR(max)= 'Q1 PK1 ITM1 D1,Q2 PK2 ITM2 D2'
DECLARE @X XML
SELECT @X = '<myxml><n><d>' +
REPLACE (@S,',','</d></n><n><d>') + '</d></n></myxml>'
SELECT SUBSTRING(x,firstSpace,secondSpace-firstSpace) + ' ' +
SUBSTRING(x,1,firstSpace) + ' ' +
SUBSTRING(x,secondSpace,len(x))
FROM ( --Getting CharIndex of first and second spaces
SELECT x, CHARINDEX(' ',x,1) firstSpace, CHARINDEX(' ',x,CHARINDEX(' ',x,1)+1) secondSpace
FROM ( --Spliting by "," into records
SELECT C.value('d[1]','VARCHAR(50)') x
FROM @X.nodes('/myxml/n') Cols (C) ) T1
) T2
--Data
'Q1 PK1 ITM1 D1,Q2 PK2 ITM2 D2'
--Results
'PK1 Q1 ITM1 D1'
'PK2 Q2 ITM2 D2'
如果您想将它们拆分成列,请尝试此操作;
DECLARE @S VARCHAR(500)= 'Q1 PK1 ITM1 D1,Q2 PK2 ITM2 D2'
DECLARE @X XML
SELECT @X = '<myxml><n><d>' +
REPLACE(REPLACE (@S,',','</d></n><n><d>'), ' ', '</d><d>') +
'</d></n></myxml>'
SELECT C.value('d[2]','VARCHAR(50)') PK,
C.value('d[1]','VARCHAR(50)') Qty,
C.value('d[3]','VARCHAR(50)') Item,
C.value('d[4]','VARCHAR(50)') Description
FROM @X.nodes('/myxml/n') Cols (C)
--Data
'Q1 PK1 ITM1 D1,Q2 PK2 ITM2 D2'
--Results
PK1 | Q1 | ITM1 | D1
PK2 | Q2 | ITM2 | D2