2009-03-27 25 views
6

Puedo encontrar muchos ejemplos sobre cómo importar ciertos tipos de datos XML en SQL Server 2005. Pero me han dado datos en el siguiente formato (repitiendo "fila" y "celda" con ID's en lugar de las etiquetas sido nombrado etc:Importación de XML en SQL Server

<?xml version="1.0"?> <rows> 
    <row id='1'> 
     <cell id='category'>Simple</cell> 
     <cell id='query'>summary</cell> 
     <cell id='clientsfound'>6</cell> 
     <cell id='eligibleclients'>11</cell> 
     <cell id='percentage'>55</cell> 
     <cell id='days'>0</cell> 
    </row> 

    <row id='2'> 
     <cell id='category'>Complex</cell> 
     <cell id='query'>details</cell> 
     <cell id='clientsfound'>4</cell> 
     <cell id='eligibleclients'>6</cell> 
     <cell id='percentage'>67</cell> 
     <cell id='days'>5</cell> 
    </row> 

    ... 
    </rows> 

lo ideal sería que desea cargar en una tabla, tales como:?

CREATE TABLE [dbo].[QueryResults](
    [UserString] [varchar](50) NULL, 
    [ImportStamp] [timestamp] NULL, 
    [RowID] [int] NULL, 
    [Category] [nchar](10) NULL, 
    [Query] [nchar](10) NULL, 
    [ClientsFound] [int] NULL, 
    [EligibleClients] [int] NULL, 
    [Percentage] [int] NULL, 
    [Days] [int] NULL 
) 

alguien me puede proporcionar con un ejemplo o punto a hacia un tutorial en línea

Respuesta

1

Puedes hacerlo usando OPENXML y XQUERY.

DECLARE @XMLdoc XML 
DECLARE @idoc int 
SELECT @XMLdoc = '<?xml version="1.0"?> 
    <rows> 
    <row id="1"> 
     <cell id="category">Simple</cell> 
     <cell id="query">summary</cell> 
     <cell id="clientsfound">6</cell> 
     <cell id="eligibleclients">11</cell> 
     <cell id="percentage">55</cell> 
     <cell id="days">0</cell> 
    </row> 
    <row id="2"> 
     <cell id="category">Complex</cell> 
     <cell id="query">details</cell> 
     <cell id="clientsfound">4</cell> 
     <cell id="eligibleclients">6</cell> 
     <cell id="percentage">67</cell> 
     <cell id="days">5</cell> 
    </row> 
    </rows>' 


-- Create an internal representation of the XML document. 
EXEC sp_xml_preparedocument @idoc OUTPUT, @XMLDoc 

INSERT INTO QueryResults (RowID,Category,Query,ClientsFound,EligibleClients,Percentage,Days) 
SELECT id, 
     overflow.value('(/row/cell[@id="category"])[1]', 'nchar(10)'), 
     overflow.value('(/row/cell[@id="query"])[1]', 'nchar(10)'), 
     overflow.value('(/row/cell[@id="clientsfound"])[1]', 'int'), 
     overflow.value('(/row/cell[@id="eligibleclients"])[1]', 'int'), 
     overflow.value('(/row/cell[@id="percentage"])[1]', 'int'), 
     overflow.value('(/row/cell[@id="days"])[1]', 'int') 
FROM OPENXML (@idoc, '/rows/row',10) 
WITH (id int '@id', 
    overflow xml '@mp:xmltext' --the row xml node 
) 

-- Release resources allocated for the XML document. 
EXEC sp_xml_removedocument @idoc 

SELECT * FROM QueryResults 

Resultados:

UserString ImportStamp  RowID Category Query ClientsFound EligibleClients Percentage Days 
----------- ------------------ ------ --------- -------- ------------ --------------- ----------- ---- 
NULL  0x000000000000C1CA 1  Simple summary 6   11    55   0 
NULL  0x000000000000C1CB 2  Complex details 4   6    67   5 

no estoy seguro de lo que quiere poblada de 'UserString', pero se puede resolver eso más tarde.

Espero que esto proporcione una solución adecuada a su pregunta.

- Disculpe gbn, probablemente tenga razón sobre sp_xml_preparedocument. Acabo de tomar este enfoque de algunos procesos almacenados similares que teníamos en un proyecto en el que trabajamos con el equipo de Microsoft SDC, así que pensé que sería seguro. Tu enfoque es probablemente más limpio de todos modos.

+0

No hay necesidad de utilizar sp_xml_preparedocument en SQL 2005 cambios de manejo – gbn

+0

XML son una de las mejores características de SQL Server 2005 ... :-) – gbn

9

El xml debe ser "" no "internamente, ¿no?

De todos modos, puede analizar el tipo de datos XML de forma nativa. sp_xml_preparedocument es francamente peligroso debido a la sobrecarga de uso de la memoria.

DECLARE @foo XML; 

SET @foo = N'<?xml version="1.0"?> 
<rows> 
    <row id="1"> 
     <cell id="category">Simple</cell> 
     <cell id="query">summary</cell> 
     <cell id="clientsfound">6</cell> 
     <cell id="eligibleclients">11</cell> 
     <cell id="percentage">55</cell> 
     <cell id="days">0</cell> 
    </row> 
    <row id="2"> 
     <cell id="category">Complex</cell> 
     <cell id="query">details</cell> 
     <cell id="clientsfound">4</cell> 
     <cell id="eligibleclients">6</cell> 
     <cell id="percentage">67</cell> 
     <cell id="days">5</cell> 
    </row> 
</rows>'; 

SELECT 
    x.item.value('@id', 'int') AS RowID, 
    y.item.value('(./cell[@id="category"])[1]', 'nchar(10)') AS category, 
    y.item.value('(./cell[@id="query"])[1]', 'nchar(10)') AS query, 
    y.item.value('(./cell[@id="clientsfound"])[1]', 'int') AS clientsfound, 
    y.item.value('(./cell[@id="eligibleclients"])[1]', 'int') AS eligibleclients, 
    y.item.value('(./cell[@id="percentage"])[1]', 'int') AS percentage, 
    y.item.value('(./cell[@id="days"])[1]', 'int') AS days 
FROM 
    @foo.nodes('/rows/row') x(item) 
    CROSS APPLY 
    x.item.nodes('.') AS y(item) 
Cuestiones relacionadas