10 June 2013
Sometimes there is a requirement to insert multiple values in the database. This can be done using bulk insert, table-valued functions, through XML, or simply by calling an insert procedure that inserts a single item multiple times. In this post we will be taking a look at how to do multiple inserts using a single query through XML using SQL Server 2008.
Let’s say you have an XML chunk that looks like this:
<AppUsers>
<AppUser>
<Username>awesome username</Username>
<Email>awesome email</Email>
<FirstName>awesome firstname</FirstName>
<LastName>awesome lastname</LastName>
</AppUser>
<AppUser>
<Username>amazing username</Username>
<Email>amazing email</Email>
<FirstName>amazing firstname</FirstName>
<LastName>amazing lastname</LastName>
</AppUser>
</AppUsers>
This is a collection of ‘appuser’ nodes, with the root node ‘appusers’. Each appuser has a username, email, firstname, and lastname.
Let’s select this XML in SQL Server. First, we turn it into the SQL XML type:
DECLARE @MyXML XML
SET @MyXML = '<AppUsers>
<AppUser>
<Username>awesome username</Username>
<Email>awesome email</Email>
<FirstName>awesome firstname</FirstName>
<LastName>awesome lastname</LastName>
</AppUser>
<AppUser>
<Username>amazing username</Username>
<Email>amazing email</Email>
<FirstName>amazing firstname</FirstName>
<LastName>amazing lastname</LastName>
</AppUser>
</AppUsers>'
Then we can use the following markup to select it:
SELECT
AppUser.value('(Username)[1]', 'Varchar(50)') AS Username,
AppUser.value('(Email)[1]', 'Varchar(50)') AS Email,
AppUser.value('(FirstName)[1]', 'Varchar(50)') AS FirstName,
AppUser.value('(LastName)[1]', 'Varchar(50)') AS LastName
FROM
@MyXML.nodes('/AppUsers/AppUser') AS X(AppUser)
Which gives us the very nice result of:
Username Email FirstName LastName
---------------------------------- ---------------------------------- ---------------------------------- ----------------------------------
awesome username awesome email awesome firstname awesome lastname
amazing username amazing email amazing firstname amazing lastname
Let’s take a look at the syntax used to select the XML. Let’s begin with the FROM statement.
For the FROM statement:
For the SELECT statement:
Just like any other SELECT statement, you can combine this with an INSERT INTO statement in order to insert the values into a table. And of course, you can use this to create a stored procedure whose input will be XML. Just remember to declare the parameter type as XML.