gpt4 book ai didi

sql - 动态识别字符串中键值对的数量

转载 作者:行者123 更新时间:2023-12-01 00:43:53 26 4
gpt4 key购买 nike

我需要采用管道分隔的键值对字符串并转换列中的数据。

我有一种可以使用的工作方法,但是这假设传入数据在每次交付时的结构都相同,如果添加新的键值对,则需要更新,我想在 future 尽可能多地证明它.

这是 DDL 和示例数据以及我迄今为止所使用的解决方案。

DDL:

    CREATE TABLE #pipers (team_id nvarchar(50), piped_string nvarchar(250))

样本数据:
    INSERT INTO #pipers (team_id, piped_string) VALUES 
(newid(), 'team_name:Brighton|stadium:American Express Community Stadium|max_attendance:30750')
,(newid(), 'team_name:Middlesbrough|stadium:Riverside|max_attendance:34742')
,(newid(), 'team_name:Derby|stadium:Pride Park Stadium|max_attendance:33597')

当前尝试:
    ;WITH xmldata (team_id, piped_string, xml_string)
AS
(
SELECT team_id
,piped_string
,CAST('<teaminfo>'+'<team>'+REPLACE(piped_string,'|','</team><team>')+'</team>'+'</teaminfo>' AS XML)
FROM #pipers
)

SELECT team_id,
piped_string,
team_name = x.xml_string.value('(/teaminfo/team)[1]','nvarchar(150)'),
stadium = x.xml_string.value('(/teaminfo/team)[2]','nvarchar(150)'),
max_attendance = x.xml_string.value('(/teaminfo/team)[3]','nvarchar(150)')
FROM xmldata x

我的问题是:我将如何动态识别传入字符串中的对数并将其应用于 XML 逻辑?

最佳答案

如果您只想知道计数,请这样做:

DECLARE @str VARCHAR(MAX)='team_name:Brighton|stadium:American Express Community Stadium|max_attendance:30750';
SELECT LEN(@str)-LEN(REPLACE(@str,'|','')) + 1;

关于sql - 动态识别字符串中键值对的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35990801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com