2017-02-22 93 views
0

我想從表中讀取一個varchar列,但此列實際上是Xml,所以我將該值轉換爲XML並試圖從那裏獲取值。獲取null嘗試讀取XML列值SQL

問題是我總是變空。這是我的代碼:

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

有幾個缺陷:

  • bad habit to kick: NOLOCK everywhere
  • 如果XML sho w我們是完整的,不需要APPLY.nodes()
  • 不要在「部分」之前使用雙重//。這會觸發深層搜索並在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 
+0

非常感謝@Shnugo你是最好的,你的回答是絕對正確的。我非常感謝你對此的幫助。所有的建議都是可悲的,因爲數據庫不是我的,所以我必須以實施的方式使用它。非常感謝。 –