2012-12-02 79 views
2

好吧,我現在有這個存儲過程的代碼。如何使用存儲過程選擇xml元素屬性?

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>標籤內的元素,就叫CustomerIdName,不存在的。

當從表中選擇所有行時,在完成該過程之後,我得到所有行但具有NULL值。

我的問題,我如何從XML獲取屬性?

在此先感謝!

回答

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) 

獲取屬性,使用領先的@

+1

謝謝!完美的作品,我會接受你在八分鐘規則後回答! – Andreas

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 
+0

不知道誰是第一個,但首先看到marc_s。感謝你的回答! – Andreas

相關問題