Home Forums Programming XML XML To SQL conversion RE: XML To SQL conversion

  • clucasi (5/28/2014)


    ...the problem I am having is that the XML has two row nodes.

    The deal with two nodes with the same name you could refer to them by their position. In this code:

    SELECTx.value('(/CommonEventData/Row[1]/CallSource)[1]','NVARCHAR(50)') AS CallSource,

    x.value('(/CommonEventData/Row[1]/CallerCityStateZipCode)[1]','NVARCHAR(50)') AS CallerCityStateZipCode,

    x.value('(/CommonEventData/Row[1]/CallerName)[1]','NVARCHAR(50)') AS CallerName,

    x.value('(/CommonEventData/Row[1]/CallerPhone)[1]','NVARCHAR(50)') AS CallerPhone,

    x.value('(/CommonEventData/Row[2]/Beat)[1]','NVARCHAR(50)') AS Beat,

    x.value('(/CommonEventData/Row[2]/MultiEventId)[1]','NVARCHAR(50)') AS MultiEventId,

    x.value('(/CommonEventData/Row[2]/PrimaryUnitId)[1]','NVARCHAR(50)') AS PrimaryUnitId

    FROM (SELECT @TXML) x(x)

    In this code, Row[1] is the First instance of the "row" node. Row[2] is the Second instance of the 'row' node.

    Since the children of row are unique (e.g. callerName, CallerPhone, etc only appear once) you can refer only to row and let the XML parser sort it out like so...

    SELECTx.value('(/CommonEventData/Row/CallSource)[1]','NVARCHAR(50)') AS CallSource,

    x.value('(/CommonEventData/Row/CallerCityStateZipCode)[1]','NVARCHAR(50)') AS CallerCityStateZipCode,

    x.value('(/CommonEventData/Row/CallerName)[1]','NVARCHAR(50)') AS CallerName,

    x.value('(/CommonEventData/Row/CallerPhone)[1]','NVARCHAR(50)') AS CallerPhone,

    x.value('(/CommonEventData/Row/Beat)[1]','NVARCHAR(50)') AS Beat,

    x.value('(/CommonEventData/Row/MultiEventId)[1]','NVARCHAR(50)') AS MultiEventId,

    x.value('(/CommonEventData/Row/PrimaryUnitId)[1]','NVARCHAR(50)') AS PrimaryUnitId

    FROM (SELECT @TXML) x(x)

    What I posted above is the most simplified.

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001