我试图从表中读取一个varchar列,但是这个列实际上是Xml,因此我将该值转换为XML并尝试从那里获取值。
问题在于我总是变空。这是我的代码:
declare @Greeting xml = (select CAST(sg.Greeting as xml) from AnsService.Ans.SiteGroup sg with (nolock) where sg.SiteGroupNum = 2032)
select
sg.AnswerAs,
(select xmlData.Col.value('.', 'varchar(max)') from @Greeting.nodes('//Section/Paragraph/Run') xmlData(col)) as Greeting
from AnsService.Ans.SiteGroup sg with (nolock)
where sg.SiteGroupNum = 2032
转换后的xml值为:
<Section xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml:space="preserve>
<Paragraph>
<Run>Thank you for calling Intelli-tec Security Services. This is [OpFirst] speaking, how may I help you?</Run>
</Paragraph>
</Section>
任何人都可以帮我识别我的问题,谢谢
答案 0 :(得分:1)
有几个缺陷:
APPLY
.nodes()
//
。这会触发深度搜索,并在XML <Section>
select CAST(sg.Greeting as xml
)试试这个:
DECLARE @Greeting XML=
N'<Section xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml:space="preserve">
<Paragraph>
<Run>Thank you for calling Intelli-tec Security Services. This is [OpFirst] speaking, how may I help you?</Run>
</Paragraph>
</Section>';
--declared namespace
SELECT
@Greeting.value('declare namespace ns1="http://schemas.microsoft.com/winfx/2006/xaml/presentation";
(/ns1:Section/ns1:Paragraph/ns1:Run/text())[1]','nvarchar(max)') Greeting;
--predefined namespace
WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com/winfx/2006/xaml/presentation')
SELECT
@Greeting.value('(/Section/Paragraph/Run/text())[1]','nvarchar(max)') Greeting;
--no namespace but wildcards
SELECT
@Greeting.value('(/*:Section/*:Paragraph/*:Run/text())[1]','nvarchar(max)') Greeting;
如果我的魔法水晶球工作正常,你需要这样的东西
select
sg.AnswerAs,
CAST(sg.Greeting AS XML).value('declare namespace ns1="http://schemas.microsoft.com/winfx/2006/xaml/presentation";
(/ns1:Section/ns1:Paragraph/ns1:Run/text())[1]','nvarchar(max)') AS Greeting
from AnsService.Ans.SiteGroup sg with (nolock)
where sg.SiteGroupNum = 2032