2017-06-23 100 views
1

我無法從保存在SQL Server數據庫中的XML文本中獲取一些數據。我的數據如下:從SQL中選擇數據來自SQL

<retConsReciCTe xmlns="http://www.portalfiscal.inf.br/cte" versao="3.00"> 
 
    <tpAmb>2</tpAmb> 
 
    <verAplic>SP-CTe-25-05-2017</verAplic> 
 
    <nRec>351000011484798</nRec> 
 
    <cStat>104</cStat> 
 
    <xMotivo>Lote processado</xMotivo> 
 
    <cUF>35</cUF> 
 
    <protCTe versao="3.00"> 
 
    <infProt> 
 
     <tpAmb>2</tpAmb> 
 
     <verAplic>SP-CTe-25-05-2017</verAplic> 
 
     <chCTe>35170623838348000310570000000058731000058731</chCTe> 
 
     <dhRecbto>2017-06-22T21:28:18-03:00</dhRecbto> 
 
     <cStat>232</cStat> 
 
     <xMotivo>Rejeição: IE do destinatário não informada</xMotivo> 
 
    </infProt> 
 
    </protCTe> 
 
</retConsReciCTe>

我要選擇僅在內容。出於這個原因,我運行下面的查詢:

select top 10 retorno_sefaz_doc.value('(/retConsReciCTe/@xmln)[1]','varchar(10)') as [retorno] from documentos

而我的回報始終是NULL。有人可以輕輕地幫我告訴我出了什麼問題?

+0

什麼是您預期的輸出? – TriV

+0

我想將內容轉換爲版本。在這種情況下,3.00 –

回答

2

你可以定義一個默認的命名空間和value得到輸出這樣

DECLARE @SampleData AS TABLE 
(
    XmlValue xml 
) 

INSERT INTO @SampleData 
(
    XmlValue 
) 
VALUES 
(N'<retConsReciCTe xmlns="http://www.portalfiscal.inf.br/cte" versao="3.00"> 
    <tpAmb>2</tpAmb> 
    <verAplic>SP-CTe-25-05-2017</verAplic> 
    <nRec>351000011484798</nRec> 
    <cStat>104</cStat> 
    <xMotivo>Lote processado</xMotivo> 
    <cUF>35</cUF> 
    <protCTe versao="3.00"> 
    <infProt> 
     <tpAmb>2</tpAmb> 
     <verAplic>SP-CTe-25-05-2017</verAplic> 
     <chCTe>35170623838348000310570000000058731000058731</chCTe> 
     <dhRecbto>2017-06-22T21:28:18-03:00</dhRecbto> 
     <cStat>232</cStat> 
     <xMotivo>Rejeição: IE do destinatário não informada</xMotivo> 
    </infProt> 
    </protCTe> 
</retConsReciCTe>') 

;WITH XMLNAMESPACES (default 'http://www.portalfiscal.inf.br/cte') 
select sd.XmlValue.value('(/retConsReciCTe/@versao)[1]','varchar(20)') 
                  AS Versao 
FROM @SampleData sd 

返回

Versao 
3.00 
+0

好!很棒!多謝!!!! –

+0

很好的解決方案,從我這邊+1,但是不需要'CROSS APPLY' ... – Shnugo

+0

是的,這是多餘的。謝謝@Shugo ... – TriV