2009-05-15 3 views
18

Attualmente sto cercando di ottenere tutti gli attributi da qualche XML con una query SQL.SQL Server: come ottenere gli attributi XML in una query?

Ho tentato quanto segue per recuperarlo, ma mi manca qualcosa di fondamentale.

DECLARE @T varchar(max) 
SET @T = 
'<root> 
    <Field FieldRowId="1000"> 
    <Items> 
     <Item Name="CODE"/> 
     <Item Name="DATE"/> 
    </Items> 
     <Attributes> 
     <Attribute ID ="1"/> 
     </Attributes> 
    </Field> 
    <Field FieldRowId="2000"> 
    <Items> 
       <Item Name="CODE"/> 
       <Item Name="DATE"/> 
    </Items> 
    <Attributes> 
     <Attribute ID ="2"/> 
    </Attributes> 
    </Field> 
</root>' 

DECLARE @X xml 

SET @X = CAST(@T as xml) 
SELECT Y.ID.value('@FieldRowId', 'int') as FieldID, 
    Y.ID.value('/Items/@Name', 'varchar(max)') as "Name", 
    Y.ID.value('/Attributes/@ID', 'int') as AttributeID 
FROM @X.nodes('/root/Field') as Y(ID) 

risposta

48

Si dovrebbe provare qualcosa di simile: (l'attributo @name è sull'elemento "Item" - non i "Elementi"!)

SET @X = CAST(@T as xml) 
SELECT 
    Y.ID.value('(@FieldRowId)[1]', 'int') as FieldID, 
    Y.ID.value('(Items/Item/@Name)[1]', 'varchar(max)') as "Name", 
    Y.ID.value('(Attributes/Attribute/@ID)[1]', 'int') as AttributeID 
FROM @X.nodes('/root/Field') as Y(ID) 

Marc

+0

Grazie mille! –

1
SELECT t1.fieldId, name, attributeId 
FROM (SELECT Y.ID.value('../../@FieldRowId', 'int') as FieldID 
    , Y.ID.value('@Name', 'varchar(max)') as Name  
FROM @T.nodes('(/root/Field/Items/Item)') as Y(ID) 
) t1 -- alias the first result 
JOIN 
(SELECT Y.ID.value('../../@FieldRowId', 'int') as FieldID 
    , Y.ID.value('@ID', 'int') as AttributeID 
FROM @T.nodes('(/root/Field/Attributes/Attribute)') as Y(ID) 
) t2 -- alias the second result 
on t1.fieldid = t2.FieldID -- join them on a common column 
+1

Ecco la tua risposta. Si prega di sapere che esiste un tipo XML su SQL in modo che non sia necessario utilizzare un varchar e quindi eseguire il cast su xml. –

+0

Questa risposta è più corretta se è necessario * tutti * i dati all'interno dell'elemento 'Field'. – Serg