gpt4 book ai didi

sql - SQL Server 2008 查询中的 XML 数据类型

转载 作者:数据小太阳 更新时间:2023-10-29 01:51:07 26 4
gpt4 key购买 nike

我在 SQL Server 中有一个表,其中一列是 XML 数据类型。表中还有其他非 XML 列。以下是存储在列中的 XML 示例:

<AdultAsthma>
<Group>
<Question text="Act Score:" ForeColor="Green" />
<Controls>
<Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black" />
<Control type="TextBox" id="txtActScore" Answer="" />
</Controls>
</Group>
</AdultAsthma>

我想要的是一个匹配表中其他列的某些值的查询,对于匹配的那些列,我想从问题节点获取文本属性,从控制节点获取答案属性。有人可以帮我解决这个问题吗?

编辑

如果我有多个组节点,需要更改什么?在这个场景中,我希望每个问题的文本和答案都与每个问题一起出现。见下文:

<AdultAsthma>
<Group>
<Question text="Act Score:" ForeColor="Green" />
<Controls>
<Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black" />
<Control type="TextBox" id="txtActScore" Answer="" />
</Controls>
</Group>
<Group>
<Question text="Do You Have Asthma?:" ForeColor="Black" />
<Controls>
<Control type="RadioButton" id="rbHaveAsthmaYes" text="Yes" GroupName="Diagnosed" ForeColor="Black" Answer="False" />
<Control type="RadioButton" id="rbHaveAsthmaNo" text="No" GroupName="Diagnosed" ForeColor="Black" Answer="False" />
</Controls>
</Group>
</AdultAsthma>

最佳答案

declare @T table
(
XMLCol xml
)

insert into @T values
('<AdultAsthma>
<Group>
<Question text="Act Score:" ForeColor="Green" />
<Controls>
<Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black"/>
<Control type="TextBox" id="txtActScore" Answer="Answer" />
</Controls>
</Group>
</AdultAsthma>
')

select XMLCol.value(N'(/AdultAsthma/Group/Question/@text)[1]', 'nvarchar(max)'),
XMLCol.value(N'(/AdultAsthma/Group/Controls/Control/@Answer)[1]', 'nvarchar(max)')
from @T

更新:

当您需要将 XML 分解为多行时,您可以在 cross apply 中使用 .nodes()

declare @T table
(
XMLCol xml
)

insert into @T values
('<AdultAsthma>
<Group>
<Question text="Act Score:" ForeColor="Green" />
<Controls>
<Control type="Label" id="txtScore" text="Enter ACT Score:" ForeColor="Black" />
<Control type="TextBox" id="txtActScore" Answer="" />
</Controls>
</Group>
<Group>
<Question text="Do You Have Asthma?:" ForeColor="Black" />
<Controls>
<Control type="RadioButton" id="rbHaveAsthmaYes" text="Yes" GroupName="Diagnosed" ForeColor="Black" Answer="False" />
<Control type="RadioButton" id="rbHaveAsthmaNo" text="No" GroupName="Diagnosed" ForeColor="Black" Answer="False" />
</Controls>
</Group>
</AdultAsthma>
')

select X.N.value(N'(Question/@text)[1]', 'nvarchar(max)'),
X.N.value(N'(Controls/Control/@Answer)[1]', 'nvarchar(max)')
from @T as T
cross apply T.XMLCol.nodes(N'/AdultAsthma/Group') as X(N)

关于sql - SQL Server 2008 查询中的 XML 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9708205/

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