devxlogo

OpenXML for Multiple Trips to the Database

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 = ''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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist