Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在SQL Server 2016中解析字符串_Sql_Sql Server_Tsql_Sql Server 2016 - Fatal编程技术网

在SQL Server 2016中解析字符串

在SQL Server 2016中解析字符串,sql,sql-server,tsql,sql-server-2016,Sql,Sql Server,Tsql,Sql Server 2016,我的存储过程中有一个分号分隔的字符串变量,其内容在下面的引号中显示,其中的短语和名称由两个破折号“-”分隔 下面是字符串变量 外部雇佣——雇佣#01;调任-外部-雇佣#15;调任-外部-雇用#21;外部雇佣——雇佣#03;内部调动——约翰·潘;外部雇佣——卡拉·艾玛 我想把它解析出来,这样它会在括号中显示与每个短语相关联的名称,用逗号分隔,以及短语出现的次数。结果示例如下所示 结果 3外部雇佣(雇佣01,雇佣03,卡拉·艾玛);2调动-外部(雇用15人,雇用21人);1次内部调动(John P

我的存储过程中有一个分号分隔的字符串变量,其内容在下面的引号中显示,其中的短语和名称由两个破折号“-”分隔

下面是字符串变量

外部雇佣——雇佣#01;调任-外部-雇佣#15;调任-外部-雇用#21;外部雇佣——雇佣#03;内部调动——约翰·潘;外部雇佣——卡拉·艾玛
我想把它解析出来,这样它会在括号中显示与每个短语相关联的名称,用逗号分隔,以及短语出现的次数。结果示例如下所示

结果

3外部雇佣(雇佣01,雇佣03,卡拉·艾玛);2调动-外部(雇用15人,雇用21人);1次内部调动(John Pen)

有点难看,但这可能会有所帮助

示例

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,'')
返回

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

真正的问题似乎是在RDBMS中存储分隔数据。看来你真的需要tom来修改设计,不管它是什么。请阅读一些关于改进你的问题的提示。您缺少一些重要的项目,例如显示您尝试的内容,并包括一个特定的编程问题。你没问题,嗨,拉鲁。我承认用分号作为分隔符的字符串变量的内容并不新奇,但这是我在处理从组合表检索到的数据后可以设计的。分号然后存储在变量表中,在变量表中进一步查询分号,然后显示分号。