Question create XML from SQL for XML format

  • Would like to create XML format from SQL table Customers(col1,col2,col3) data with 1 row Only.

    <?xml version="1.0" ?>

    <ALLRequests>

    <TopHeader>

    <Sensor user="myname" pw="mypassword" />

    </TopHeader>

    <Main>

    <NewRequest TypeOfRequest="Change">

    <NewParameter ATT="StaticV1" ATTV=Value from Col1 in Table Customers />

    <NewParameter ATT="StaticV2" ATTV=Value from Col2 in Table Customers/>

    <NewParameter ATT="StaticV3" ATTV=Value from Col3 in Table Customers/>

    </NewRequest>

    </Main>

    </ALLRequests>

    would like to create this using SQL so I can pass the resulting xml to a Stored Procedure for further execution.

    Thanks

  • Ok, we know your requirement. Now what is your question?

    The absence of evidence is not evidence of absence.
    Martin Rees

    You can lead a horse to water, but a pencil must be lead.
    Stan Laurel

  • This is one way of doing it.

    DECLARE @Customers TABLE ( Col1 varchar(50), Col2 varchar(50), Col3 varchar(50) )

    INSERT INTO @Customers ( Col1, Col2, Col3 )

    VALUES ( 'Value from Col1 in Table Customers', 'Value from Col2 in Table Customers', 'Value from Col3 in Table Customers' )

    SELECT

    'myname' AS [TopHeader/Sensor/@user],

    'mypassword' AS [TopHeader/Sensor/@pw],

    (

    SELECT

    'Change' AS [@TypeOfRequest],

    (

    SELECT X.ATT AS [@ATT], X.ColVal AS [@ATTV]

    FROM

    (

    SELECT 'StaticV1' AS ATT, Col1 AS ColVal FROM @Customers

    UNION ALL SELECT 'StaticV2' AS ATT, Col2 FROM @Customers

    UNION ALL SELECT 'StaticV3' AS ATT, Col3 FROM @Customers

    ) X

    FOR XML PATH('NewParameter'), TYPE

    )

    FOR XML PATH('NewRequest'), ROOT('Main'), TYPE

    )

    FOR XML PATH('ALLRequests'), TYPE

  • Thank you it works but how do i include the

    <?xml version="1.0" ?>

    so that i can pass this on as a XML parameter to a stored procedure.

    I appreciate your help in the matter

    regards

  • Thank you for the response.

    I forgot to add this specific:

    I need the XML declaration on top of XML String as well.

    I also want to leave out the element NewParameter for row/record where Col4 value is Null or empty

    <NewRequest TypeOfRequest="Change">

    <NewParameter ATT="StaticV1" ATTV="Value from Col1 in Table Customers" />

    <NewParameter ATT="StaticV2" ATTV="Value from Col2 in Table Customers" />

    <NewParameter ATT="StaticV3" ATTV="Value from Col3 in Table Customers" />

    </NewRequest>

    Thanks

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply