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.