简体   繁体   English

在 SQL Server 2016 中解析字符串

[英]Parse string in SQL Server 2016

I have a semi colon delimited string variable in my stored procedure with contents shown in quotes below with a phrase and name separated by two dashes "--".我的存储过程中有一个以分号分隔的字符串变量,其内容在下面的引号中显示,短语和名称由两个破折号“--”分隔。

String Variable below.下面的字符串变量。

Outside Hire--Hire #01; Reassignment - External--Hire #15; Reassignment - External--Hire #21; Outside Hire--Hire #03; Internal Reassignment--John Pen; Outside Hire--Kara Emma

I would like to parse it out such that it shows the names associated with each phrase in brackets, separated by a comma and the number of times the phrase occurs.我想对其进行解析,使其在括号中显示与每个短语相关的名称,用逗号分隔,以及该短语出现的次数。 Example of result is displayed below.结果示例如下所示。

Result结果

3 Outside Hire(Hire #01, Hire #03, Kara Emma); 2 Reassignment - External(Hire #15, Hire #21); 1 Internal Reassignment(John Pen)

A little ugly, but perhaps this will help有点难看,但也许这会有所帮助

Example例子

Declare @S varchar(max) = 'Outside Hire--Hire #01; Reassignment - External--Hire #15; Reassignment - External--Hire #21; Outside Hire--Hire #03; Internal Reassignment--John Pen; Outside Hire--Kara Emma'

;with cte as (
Select Cnt=sum(1) over (Partition By Pos1)
      ,Pos1
      ,Pos2
 From  string_split(@S,';') A
 Cross Apply (
                Select Pos1 = trim(JSON_VALUE(S,'$[0]'))
                      ,Pos2 = trim(JSON_VALUE(S,'$[1]'))
                 From  ( values ( '["'+replace(replace(Value,'"','\"'),'--','","')+'"]' ) ) A(S)
             ) B
),  cte2 as (
Select Distinct TmpStr = concat(A.cnt,' ',Pos1,'(',Stuff((Select ', ' +Pos2 From cte Where Pos1=A.Pos1 For XML Path ('')),1,2,'') ,')') 
 From  cte A
)
Select NewStr = Stuff((Select '; '+TmpStr From cte2 order by TmpStr Desc For XML Path ('')),1,2,'')

Returns退货

NewStr
3 Outside Hire(Hire #01, Hire #03, Kara Emma); 2 Reassignment - External(Hire #15, Hire #21); 1 Internal Reassignment(John Pen)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM