views:

22

answers:

1

Using a SELECT statement in MS SQL 2005 TSQL, and no source table, just variables as listed below...

@FirstName varchar(20)
@LastName varchar(20)
@ZipCode varchar(5)

...what syntax will build XML resembling the following?

<XMLDATA><REC FirstName="JOHN" LastName="SMITH" ZipCode="98052" /></XMLDATA>
+1  A: 

How about this:

DECLARE @FirstName varchar(20) 
SET @FirstName = 'JOHN'

DECLARE @LastName varchar(20)
SET @LastName = 'SMITH'

DECLARE @ZipCode varchar(5)
SET @ZipCode = '98052'

SELECT
 @FirstName AS '@FirstName',
 @LastName AS '@LastName',
 @ZipCode AS '@ZipCode'
FOR 
    XML PATH('REC'), ROOT('XMLDATA')

The FOR XML PATH('REC') defines the XML tag and the AS '@FirstName' specifies you want this value to be an attribute on that XML tag. The ROOT('XMLDATA') wraps the whole thing into yet another XML Tag on the outside.

marc_s
Perfect, thank you good sir!
Darth Continent