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.