insert data from xml column into temp table

后端 未结 3 1109

I have a xml column that look like

SET @XMLData = \'

        
3条回答
  •  执笔经年
    2021-01-07 03:17

    First of all - please use appropriate data types! If your source data is XML - why aren't you using the XML datatype?

    Also, if you have a Date in your table - why isn't that a DATE or DATETIME type?? And why is the Number a VARCHAR(50) ??

    Makes no sense......

    Then: you're not looking at the XML namespaces that are present in the XML document - but you must!

    At lastly - I would recommend using the native XQuery support instead of the legacy, deprecated sp_xml_preparedocument / OpenXML approach....

    Seems much easier, much clearer to me...

    Use this:

    -- variable declaration
    DECLARE @XMLData XML
    
    -- creating temporary table
    CREATE TABLE #TEMP_TABLE
    (
        REC_ID INT IDENTITY(1,1),
        [Id] INT,
        [Date] DATETIME2(3),
        [Number] INT
    ); 
    

    and then use proper XQuery statements, including the XML namespaces to handle the data:

    SET @XMLData = '
                        
                           1
                           0001-01-01T00:00:00
                           
                        
                        
                           42
                           2013-12-22T14:45:00
                           373
                        
                     '
    
    ;WITH XMLNAMESPACES ('http://schemas.datacontract.org/2004/07/Gbms.Dto.Bijak' AS ns1,
                    'http://schemas.datacontract.org/2004/07/Gbms.Dto' AS ns2,
                    'http://schemas.datacontract.org/2004/07/Gbms.Dto.VirginBijak' AS ns3)
    INSERT INTO #TEMP_TABLE(ID, Date, Number)
       SELECT
      xc.value('(ns2:Id)[1]', 'int'),
      xc.value('(ns3:Date)[1]', 'DateTime2'),
      xc.value('(ns3:Number)[1]', 'int')
       FROM 
      @XmlData.nodes('/ns1:ArrayOfEntityNested/ns1:EntityNested') AS xt(xc)
    

提交回复
热议问题