获取null尝试读取XML列值SQL

时间:2017-02-22 19:10:26

标签: sql sql-server xml

我试图从表中读取一个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>

任何人都可以帮我识别我的问题,谢谢

1 个答案:

答案 0 :(得分:1)

有几个缺陷:

  • bad habit to kick: NOLOCK everywhere
  • 如果您向我们展示的XML已完整,则APPLY
  • 上不需要.nodes()
  • 在&#34; Section&#34;之前不要使用双//。这会触发深度搜索,并在XML
  • 中的任何位置查找任何元素<Section>
  • 您的XML定义了默认命名空间。您必须使用它或使用通配符
  • 您应该以适当的类型存储XML。不需要演员表(例如select CAST(sg.Greeting as xml
  • 看起来好像这个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