Xml查询导致sql server出错

时间:2014-07-02 09:35:21

标签: sql sql-server xml

这是我的xml查询

declare @XML xml
set @XML=
'<ROOT>
<Customers>
<CustomerId>1111</CustomerId>
<CompanyName>Sean Chai</CompanyName>
<City>NY</City>
</Customers>
<Customers>
<CustomerId>1112</CustomerId>
<CompanyName>Tom Johnston</CompanyName>
<City>LA</City>
</Customers>
<Customers>
<CustomerId>1113</CustomerId>
<CompanyName>Institute of Art</CompanyName>
</Customers>
</ROOT>';

SELECT
R.Node('.').value('(/Customers/CustomerId/.)[1]','varchar(100)') AS CustomerID,
R.Node('.').value('(/Customers/CompanyName/.)[1]','varchar(100)') AS CompanyName
FROM @XML.nodes('/ROOT/Customers') R(Node)

但它给出错误:

Msg 4121, Level 16, State 1, Line 20
Cannot find either column "R" or the user-defined function or aggregate "R.Node", or the name is ambiguous.

我搜索但无法得到R.node事情请有人指导我这个!

我不理解@XML.nodes('/ROOT/Customers') R(Node)

它在查询中的用途是什么!

1 个答案:

答案 0 :(得分:1)

像这样更改查询并尝试

SELECT
R.Node.value('(CustomerId/.)[1]','varchar(100)') AS CustomerID,
R.Node.value('(CompanyName/.)[1]','varchar(100)') AS CompanyName
FROM @XML.nodes('/ROOT/Customers')  R(Node)

首先,您的查询中存在语法错误。您将结果表的别名作为R(节点),然后您不能将路径指定为R.Node(。)。 其次,您在查询中提到的路径是错误的(/ Customers / CustomerId /.)