[英]How do I select xml element attributes using a stored procedure?
Ok, I have this code for the stored procedure right now. 好的,我现在有了存储过程的代码。
ALTER PROC [dbo].[Readxml]
@xmlparam XML
AS
BEGIN
SET NOCOUNT ON
DECLARE @CustomerXml AS XML
SET @CustomerXml = @xmlparam
INSERT INTO Custtable.dbo.SPCustomer
(
CustomerId,
CustomerName
)
SELECT
Customer.attribute.value('CustomerId[1]', 'nvarchar(255)') AS CustomerId,
Customer.attribute.value('Name[1]', 'nvarchar(255)') AS CustomerName
FROM
@xmlparam.nodes('Customers/Customer') AS Customer(attribute)
END
My XML looks like this (simplified). 我的XML看起来像这样(简化)。
<Customers>
<Customer CustomerId="94" Name="name1" />
<Customer CustomerId="95" Name="name2" />
<Customer CustomerId="96" Name="name3" />
</Customers>
With my code right now I am not able to get the attribute values, as I understand I am trying to get elements inside the <Customer>
tag, called CustomerId
and Name
, that don't exist. 现在,使用我的代码,我无法获取属性值,因为据我了解,我试图获取<Customer>
标记内名为CustomerId
和Name
元素,这些元素不存在。
When selecting all rows from the table, after the procedure is done, I get all the rows but with NULL values. 当从表中选择所有行时,完成该过程后,我将获得所有行,但具有NULL值。
My question, how do I get the attributes from the XML? 我的问题是,如何从XML获取属性?
Thanks in advance! 提前致谢!
You need this: 你需要这个:
SELECT
Customer.attribute.value('@CustomerId', 'nvarchar(255)') AS CustomerId,
Customer.attribute.value('@Name', 'nvarchar(255)') AS CustomerName
FROM
@xmlparam.nodes('Customers/Customer') AS Customer(attribute)
To get the attribute, use a leading @
要获取属性,请使用前导@
ALTER PROC [dbo].[Readxml]
@xmlparam XML
AS
BEGIN
SET NOCOUNT ON
DECLARE @CustomerXml AS XML
SET @CustomerXml = @xmlparam
INSERT INTO Custtable.dbo.SPCustomer
(
CustomerId,
CustomerName
)
SELECT Customer.attribute.value('@CustomerId', 'BIGINT') AS CustomerId,
Customer.attribute.value('@Name', 'nvarchar(255)') AS CustomerName
FROM @xmlparam.nodes('Customers/Customer') AS Customer(attribute)
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.