Parse XML With SQL Server

Facebooktwitterredditpinterestlinkedinmail

SQL Server has a lot of useful functionality built-in when it comes to XML.  Today I want to show you an easy way to parse XML data in to a usable format inside your query.

 
For this example, I will be parsing XML data into a temp table, then inserting that data in to a table.

DECLARE	@XMLToParse  XML

-- Load the XML data in to a variable to work with.
-- This would typically be passed as a parameter to a stored proc
SET	@XMLToParse =	'<Animals>
			   <LandAnimals>
				<Animal>Baboon</Animal>
				<Animal>Yak</Animal>
				<Animal>Zebra</Animal>
			   </LandAnimals>
			</Animals>'

-- Declare temp table to parse data into
DECLARE	@ParsingTable  TABLE
	(Animal	VARCHAR(100))

-- Parse the XML in to the temp table declared above
INSERT
INTO	@ParsingTable
	(Animal)
SELECT	xmlData.A.value('.', 'VARCHAR(100)') AS Animal
FROM	@XMLToParse.nodes('Animals/LandAnimals/Animal') xmlData(A)

-- Insert into the actual table from the temp table

INSERT
INTO	Animals
	(AnimalName)
SELECT	Animal
FROM	@ParsingTable

 
The statement that parses the XML has 2 parts to it.

FROM   @XMLToParse.nodes('Animals/LandAnimals/Animal') xmlData(A)

This part says to parse the @XMLToParse variable (previously filled with the XML file) using the method built in to SQL Server called .nodes.  It specifies the repeating node to be Animals/LandAnimals/Animal.  It assigns an aliases this XML parsed records as a table named xmlData.  The (A) is the column name of the rowset.  This will be referenced in the select part of the statement.

 

SELECT  xmlData.A.value('.', 'VARCHAR(100)') AS Animal

The select part of this statement references xmlData (which is the table aliases) and A (which is the column named for that table).  It calls the .value function to return the value from the table/column.  For the .value function, you pass in 2 elements.

The first element is the field.  In this case we are passing in just a period.  We do this because there is no node below the Animal node.  If there was, we would need to specify it here..

The second parameter is the datatype that you would like the value to be casted as.  Then I always aliases the field to something relevant.

 
Although parsing XML can be a little confusing in SQL Server, it is very powerful.  This is a great way to pass bulk data to a stored procedure from any type of client application.

Cannot Insert Explicit Value For Identity Column

Facebooktwitterredditpinterestlinkedinmail

If you try to insert in to a table with an ID column, you could get this error “Cannot insert explicit value for identity column in table ‘<<table>>’ when IDENTITY_INSERT is set to OFF.”  This is not the end of the world and is actually pretty easy to get around.

 
Why Are You Getting This Error?

The reason you’re getting this error is because you are trying to tell SQL Server what the ID value for a row in the table should be.  If you have an identity column on your table, SQL Server will want to generate that ID value for you automatically.  The error is essentially saying, “Hey, I’m supposed to generate the ID for you… you aren’t supposed to tell me what it is!”

 
How Can You Fix This?

There are two easy ways to get around this.

 
If You Want To Tell SQL Server What The ID Value Should Be

If want to specify what the ID values should be for the records you are inserting, then before you execute the INSERT statement, you need to run a small sql command to turn identity inserts on.  Identity inserts allow you to populate the value of an identity column with a specific value.

SET		IDENTITY_INSERT Animal ON

INSERT
INTO	Animal
		(AnimalID, AnimalName)
VALUES	(1,        'Horse'),
		(2,        'Pig'),
		(3,        'Cow')

SET		IDENTITY_INSERT Animal OFF

NOTE: You can only have identity insert on for one table at a time.  To insert in to a second table, you will need to turn the identity insert off on the first table before inserting in to the second table.

 
If You Want To Allow SQL Server To Generate The ID

If you don’t care about what the ID values are for these records, you should just allow SQL Server to generate the ID values for you.  To do this, just specify the columns that are in the table and leave off the identity column.

INSERT
INTO	Animal
		(AnimalName)
VALUES	('Horse'),
		('Pig'),
		('Cow')

 
Reference: http://msdn.microsoft.com/en-us/library/ms188059.aspx

Insert Multiple Rows Of Static Text At One Time

Facebooktwitterredditpinterestlinkedinmail

Have you ever wanted to insert more than one row of static text in to a SQL table using the VALUES argument?  Well, this is actually pretty easy to do.  To do this you just need to pass a comma delimited value list like in the example below.

Syntax

INSERT
INTO   Employees
       (LastName,  FirstName)
VALUES ('Gump',    'Forrest'),
       ('Taylor',  'Dan'),
       ('Blue',    'Bubba')