gpt4 book ai didi

sql-server - XPath 从 sql 表列中读取值

转载 作者:数据小太阳 更新时间:2023-10-29 02:10:06 24 4
gpt4 key购买 nike

我在下面的 xml 中显示为名为 tblUsers 的表的列(Name UserBody)值。

我必须在 SQL 中使用 Xpath 读取 NewUserType 名称,即“SampleUserName”。

<UserTypeAdded xmlns="http://schemas.datacontract.org/2004/07/ABC.Domain.Contract.EventModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<UserTypeTypeDetails xmlns:a="http://schemas.datacontract.org/2004/07/ABC.Common.Contract">
<a:Id>550d9a76-3d7d-49f6-9243-f0473d32b123</a:Id>
<a:Name>Special User Types</a:Name>
</UserTypeTypeDetails>
<NewUserType xmlns:a="http://schemas.datacontract.org/2004/07/ABC.Domain.Contract.Base">
<Id xmlns="http://schemas.datacontract.org/2004/07/ABC.Common.Contract">dfa090ff-9756-42fd-be9b-02ac8c6b123</Id>
<Name xmlns="http://schemas.datacontract.org/2004/07/ABC.Common.Contract">SampleUserName</Name>
</NewUserType>
</UserTypeAdded>

我尝试使用下面的语句

   SELECT 
[UserBody].value('(/UserTypeAdded/NewUserType/Name[1])', 'nvarchar(max)') as UserName
FROM tblUsers

但运气不好

最佳答案

您错误地定义了您的节点,您有:

'(/UserTypeAdded/NewUserType/Name[1])'

您要么需要指定每个元素的位置:

'(/UserTypeAdded[1]/NewUserType[1]/Name[1])'

或者将整个路径包裹在括号中并为其指定位置:

'(/UserTypeAdded/NewUserType/Name)[1]'

您还需要定义您的 XML 命名空间:

-- SAMPLE DATA
DECLARE @tblUsers TABLE (UserBody XML);
INSERT @Tblusers
VALUES('<UserTypeAdded xmlns="http://schemas.datacontract.org/2004/07/ABC.Domain.Contract.EventModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<UserTypeTypeDetails xmlns:a="http://schemas.datacontract.org/2004/07/ABC.Common.Contract">
<a:Id>550d9a76-3d7d-49f6-9243-f0473d32b123</a:Id>
<a:Name>Special User Types</a:Name>
</UserTypeTypeDetails>
<NewUserType xmlns:a="http://schemas.datacontract.org/2004/07/ABC.Domain.Contract.Base">
<Id xmlns="http://schemas.datacontract.org/2004/07/ABC.Common.Contract">dfa090ff-9756-42fd-be9b-02ac8c6b123</Id>
<Name xmlns="http://schemas.datacontract.org/2004/07/ABC.Common.Contract">SampleUserName</Name>
</NewUserType>
</UserTypeAdded>');

-- QUERY
WITH XMLNAMESPACES
( 'http://schemas.datacontract.org/2004/07/ABC.Domain.Contract.Base' AS a,
'http://schemas.datacontract.org/2004/07/ABC.Common.Contract' AS x,
DEFAULT 'http://schemas.datacontract.org/2004/07/ABC.Domain.Contract.EventModel'
)
SELECT *,
UserBody.value('(/UserTypeAdded/NewUserType/x:Name)[1]', 'nvarchar(max)') as UserName
FROM @TblUsers;

您还可以对命名空间使用通配符:

SELECT *,
UserBody.value('(/*:UserTypeAdded/*:NewUserType/*:Name)[1]', 'nvarchar(max)') as UserName
FROM @TblUsers;

关于sql-server - XPath 从 sql 表列中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37414452/

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