sql >> Base de Datos >  >> RDS >> Sqlserver

iterando datos XML en el servidor sql 2005

Suponiendo que su XML de muestra se vea así:

<MissingDS>
  <MissingTable>
    <MissingColumn>abc</MissingColumn>
    <TableName>tblMyTable</TableName>
    <PhysicalColName>table_abc</PhysicalColName>
    <Grantor_Grantee>nobody</Grantor_Grantee>
  </MissingTable>
  <MissingTable>
    <MissingColumn>xyu</MissingColumn>
    <TableName>tblMyTable2</TableName>
    <PhysicalColName>table_xyz</PhysicalColName>
    <Grantor_Grantee>nobody2</Grantor_Grantee>
  </MissingTable>
</MissingDS>

Entonces podría analizar esto con el nuevo soporte de SQL Server 2005 XQuery de esta manera:

DECLARE @MissingXML XML
SET @MissingXML = CAST(@MissingRecordsXML AS XML)

SELECT
    Missing.Rec.value('(MissingColumn)[1]', 'varchar(1000)') AS 'MissingColumn',
    Missing.Rec.value('(TableName)[1]', 'varchar(100)') AS 'TableName',
    Missing.Rec.value('(PhysicalColName)[1]', 'varchar(100)') AS 'Physical',
    Missing.Rec.value('(Grantor_Grantee)[1]', 'varchar(100)') AS 'Grantor_Grantee'
FROM
    @MissingXML.nodes('/MissingDS/MissingTable') AS Missing(Rec)

Por supuesto, si puede SELECCIONARLO, también puede INSERTAR esas mismas filas de datos en una tabla con bastante facilidad:

INSERT INTO 
  dbo.MissingDSTable(MissingColumn, TableName, PhysicalColName, Grantor_Grantee)
    SELECT
       Missing.Rec.value('(MissingColumn)[1]', 'varchar(1000)') AS 'MissingColumn',
       Missing.Rec.value('(TableName)[1]', 'varchar(100)') AS 'TableName',
       Missing.Rec.value('(PhysicalColName)[1]', 'varchar(100)') AS 'Physical',
       Missing.Rec.value('(Grantor_Grantee)[1]', 'varchar(100)') AS 'Grantor_Grantee'
    FROM
       @MissingXML.nodes('/MissingDS/MissingTable') AS Missing(Rec)

Espero que esto ayude un poco

Marc