2

好的,我现在有这个存储过程的代码。

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

我的 XML 看起来像这样(简化)。

<Customers>
  <Customer CustomerId="94" Name="name1" />
  <Customer CustomerId="95" Name="name2" />
  <Customer CustomerId="96" Name="name3" />
</Customers>

使用我的代码现在我无法获取属性值,据我所知,我正在尝试获取<Customer>标签内的元素,称为CustomerIdand Name,它们不存在。

从表中选择所有行时,在过程完成后,我得到所有行但具有 NULL 值。

我的问题是,如何从 XML 中获取属性?

提前致谢!

4

2 回答 2

3

你需要这个:

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)

要获取属性,请使用前导@

于 2012-12-02T19:04:30.340 回答
1
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
于 2012-12-02T19:05:03.180 回答