0

Given two tables:

T1( EntityID int , EmailAddress varchar(55),MaxNumberOfConnections int )

T2( EntityID int , EntityAttributes XML )

How do I insert all the data from T1 into T2 with a single statement in such a way that all the columns in T1 (all but EntityID ) are converted into one XML column in T2 :

T1( 1,'[email protected]',454)

T2(1, '<Attributes>
          <Attribute EmailAddress="[email protected]">
          <Attribute MaxNumberOfConnections ="454">
      </Attributes>' )
3
  • Does the XML need to be in exactly that format? By reusing the element Attribute, but using different attributes, you're providing a different definition for the same name. Could you combine into a single Attribute element with multiple attributes (for the fields), or use an element for EmailAddress, MaxNumberOfConnections, etc? Commented Oct 4, 2012 at 19:43
  • XML schema doesn't have to be exactly as the one I show here. Commented Oct 4, 2012 at 21:31
  • Then post your exact schema, how then you expect to get an accurrate answer? Commented Oct 5, 2012 at 6:06

1 Answer 1

1

Here are two solutions based upon my comment - Single "Attribute" element with multiple attributes:

SELECT
    EntityId,
    (
        SELECT
            EmailAddress AS [Attribute/@EmailAddress],
            MaxNumberOfConnections AS [Attribute/@MaxNumberOfConnections]
        FROM
            T1 i
        WHERE
            i.EntityId = o.EntityId
        FOR XML PATH('Attributes')
    ) AS EntityAttributes 
FROM
    T1 o

Individual element for each field:

SELECT
    EntityId,
    (
        SELECT
            EmailAddress,
            MaxNumberOfConnections
        FROM
            T1 i
        WHERE
            i.EntityId = o.EntityId
        FOR XML PATH('Attributes')
    ) AS EntityAttributes 
FROM
    T1 o
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.