Twitter

Follow SQLQuill on Twitter

Subscribe

MN Pass

XML Data via Service Broker

I’ve been working on some development work.  This involves service broker messages and XML data.  We wanted the XML data in basically the same format as the table, but with an additional root tag on it.  To automate testing, I started digging into how to return XML via TSQL.  The FOR XML AUTO, ELEMENTS option almost worked, except we needed a root element added to it.  I toyed with the idea of converting to varchar, adding tags on the ends and converting back to XML – it would have worked, but that’s a hack.  I went back to the basics and reviewed the Basic Syntax of the FOR XML Clause and found the root clause. Here’s an example of what I needed:

 Create table ATest
(iID int identity(1,1),
Descripton varchar(50));

Insert ATest Values ('test1'),
('test2'),
('test3');

Select * from ATest FOR XML RAW ('ATEST'), ELEMENTS, ROOT('ATESTING');

This output is what I wanted:

<atesting>
	<atest>
		<iID>1</iID>
		<descripton>test1</descripton>
	</atest>
	<atest>
		<iID>2</iID>
		<descripton>test2</descripton>
	</atest>
	<atest>
		<iID>3</iID>
		<descripton>test3</descripton>
	</atest>
</atesting>

SQL 2008 Certified

I took my 70-453 test, Upgrade: Transition Your MCITP SQL Server 2005 DBA to MCITP SQL Server 2008, yesterday and passed, so it’s official: