问题描述
我在sql Server 2012上工作,我遇到问题,我无法更新状态不匹配的字符,其中部分密钥不等于基于组ID的签名密钥字符。
组ID表示为: $ $ C $ $ $ ** $ (1 = ,2 = ,3 = C,4 = ,5 = ,6 = **,7 = )
Signature Key Group Id Portion Key status Signature Key(group Id 3) Reason
*$*$C$***$**$**$* 3 s wrong C s <> C
如上一行在状态上给我错误的匹配字符,因为签名密钥上的组ID 3将是 C和部分键是s字符,因此我将使用错误的匹配字符更新状态,因为s不等于c
数据样本:
Create table #Ref
(
SignatureKey nvarchar(50),GroupId int,PortionKey nvarchar(50),Status nvarchar(100)
)
insert into #Ref(SignatureKey,GroupId,PortionKey,status)
values
('*$*$C$***$**$**$*',3,'s',NUll),('*$*$*$FG$*$**$*',4,'F',('*$*$*$***$*$D$*',6,'D',('*$*$*$***$***$**$*',2,'g',('*$**$*$***$L$**$*',5,'f',NUll)
预期结果:
Signature Key Group Id Portion Key Status
*$*$C$***$**$**$* 3 s wrong Match chatterers
*$*$*$FG$*$**$* 4 F wrong Match chatterers
*$*$*$***$*$D$* 6 D wrong Match chatterers
*$*$*$***$***$**$* 2 g wrong Match chatterers
*$**$*$***$L$**$* 5 f wrong Match chatterers
Create FUNCTION [dbo].[fn_split_string]
(
@string nvarchar(max),@delimiter nvarchar(max)
)
RETURNS TABLE AS RETURN
(
SELECT
--ROW_NUMBER ( ) over(order by (select 0)) AS id -- intuitive,but not correect
Split.a.value('let $n := . return count(../*[. << $n]) + 1','int') AS id,Split.a.value('.','NVARCHAR(MAX)') AS value
FROM
(
SELECT CAST('<X>'+REPLACE(@string,@delimiter,'</X><X>')+'</X>' AS XML) AS String
) AS a
CROSS APPLY String.nodes('/X') AS Split(a)
)
如何根据我的示例进行调用
select * from [dbo].[fn_split_string]('*$*$C$***$**$**$*','$') pc
解决方法
我已经从在线借用了一个字符串拆分功能(链接:https://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648)
该函数返回一个拆分字符串表。例如,如果我运行
SELECT * FROM dbo.Split('*$**$*$***$L$**$*','$')
返回的结果是:
一旦您具有拆分字符串的功能,就可以使用CROSS APPLY对表中的所有行运行它。
declare @Ref table
(
SignatureKey nvarchar(50),GroupId int,PortionKey nvarchar(50),Status nvarchar(100)
)
insert into @Ref(SignatureKey,GroupId,PortionKey,status)
values
('*$*$C$***$**$**$*',3,'s',NUll),('*$*$*$FG$*$**$*',4,'F',('*$*$*$***$*$D$*',6,'D',('*$*$*$***$***$**$*',2,'g',('*$**$*$***$L$**$*',5,'f',NUll)
select r.*,f.*,case
when r.PortionKey = f.Data then 'match' else 'not match'
end
from @Ref r
cross apply
dbo.Split(r.SignatureKey,'$') f where r.GroupId = f.Id
结果集为:
希望这会有所帮助。