Saturday, February 17, 2018

MS SQL - Dynamic Table Columns Generated from SQL's XML Field

I was working on a project where I needed to archive various XML documents for various applications. The main concept was to store all XMLs in one table as a varbinary and their meta data would be stored in a smaller XML field called 'XMLProps'.

Key Requirements:
- Each application could have different meta data fields, but an application's fields must be the same for all of its data
- Application's meta data needs to be searchable, and the columns returned will need to be the meta data's XML fields
- All applications will store their XML data and meta data in one table

Key Issue Being Solved:
- This solution returns a table using the XML's SQL fields as the columns; thus producing dynamic columns per application.

Here's the SQL Fiddle (For those who want to play): http://sqlfiddle.com/#!18/35637/1/0

Here's the code with comments: