如何从表中选择xml类型?

时间:2014-11-12 20:43:34

标签: sql sql-server tsql xml-parsing

我可以得到我需要的值如下:

DECLARE @xml xml;
SELECT TOP 1  @xml = InaSuQtyXml 
FROM csn_inventory..tblInventoryCache_st4 
WHERE InaDateUpd > '2014-11-01' and InaQty > 0;

SELECT b.value('@SuID', 'int') SuID, b.value('@Quantity', 'int') Quantity
FROM @xml.nodes('/Inventory/Supplier') as a(b);`

它返回:

SuID | Quantity
-----+---------
 275 | 333
7417 | -1
15203| 48

但是,当我尝试执行相同操作并从表中提取更多信息时,我收到一条错误消息,上面写着"nodes" is not a valid function, property, or field.

SELECT
TOP 1
    InaPrSKU,
    InaDateUpd,
    (InaSuQtyXml).nodes('/Inventory/Supplier').value('@SuID', 'int') SuID,
    (InaSuQtyXml).nodes('/Inventory/Supplier').value('@Quantity', 'int') Quantity
FROM csn_inventory..tblInventoryCache_st4 
WHERE InaDateUpd > '2014-11-01' and InaQty > 0;

我希望查询会产生以下结果,但它似乎不起作用。有没有办法得到以下内容?

InaPruSKU | InaDateUpd | SuID | Quantity
----------+------------+------+---------
  AA1433  | 2014-11-10 | 275  | 333
  AA1433  | 2014-11-10 | 7417 | -1
  AA1433  | 2014-11-10 | 15203| 48

1 个答案:

答案 0 :(得分:1)

您需要让cross apply从select函数中获取node函数的值。尝试更改您的查询。

SELECT TOP 1 InaPrSKU,
             InaDateUpd,
             SuID = Container.value('(SuID)[1]', 'INT'),
             Quantity = Container.value('(Quantity)[1]', 'INT'),
FROM   csn_inventory..tblInventoryCache_st4
       CROSS apply InaSuQtyXml.nodes('/Root/Inventory/Supplier') AS T1 (Container)
WHERE  InaDateUpd > '2014-11-01'
       AND InaQty > 0; 

示例:

CREATE TABLE T
  (c3 XML)

INSERT INTO t
            (c3)
VALUES     ('<Root>
<ProductDescription ProductID="1" ProductName="Road Bike">
<Features>
  <Warranty>1 year parts and labor</Warranty>
  <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>
</Features>
</ProductDescription>
</Root>')

SELECT Warranty = Container.value('(Warranty)[1]', 'varchar(50)'),
       Maintenance = Container.value('(Maintenance)[1]', 'varchar(100)')
FROM   T
       CROSS apply c3.nodes('/Root/ProductDescription/Features') AS T1 (Container)