Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Enterprise
Expertise: Advanced
Oct 11, 2002

OpenXML for Multiple Trips to the Database


Suppose you need to make multiple inserts (or updates or deletes) to a SQL Server database—for instance, inserting items in a shopping cart. In the past, you needed to loop through your code and make multiple calls to the database. This can be expensive, especially if you're talking about hundreds of records.

However, a new feature in SQL Server 2000 allows you to pass an XML document as a parameter to a stored procedure where it is treated as a table.

Paste the following code into the query analyzer and run it against the pubs database:
 
DECLARE	@sXML varchar(1000)

	SET @sXML = '<xml><store store_id=''8342'' store_name=''test insert store
name''/></xml>'
DECLARE @hDoc int

	EXEC sp_xml_preparedocument @hDoc OUTPUT, @sXML
		INSERT INTO Stores (stor_id, stor_name)

      		SELECT *
     		 FROM OPENXML(@hDoc, '/xml/store')
             			WITH
			(
			my_var_storeid char(4) '@store_id',
			my_var_storename varchar(40) '@store_name'
			)
		XMLStore --alias the new xml table

     	EXEC sp_xml_removedocument @hDoc

In the real world, you wouldn't do just 1 record because there is some over head involved in transforming the XML. However, OpenXML is a good solution when multiple calls to the database would be needed.
Thomas Messina
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date