Skip to content

Instantly share code, notes, and snippets.

@fcmendoza
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcmendoza/6ea12818740acce13776 to your computer and use it in GitHub Desktop.
Save fcmendoza/6ea12818740acce13776 to your computer and use it in GitHub Desktop.
Parse XML to SQL with attributes
declare @NotesXml xml =
'<root>
<Notes CreationDate="01/18/2015" Note="Note 1" UserID="10"/>
<Notes CreationDate="01/18/2015" Note="Note 2" UserID="20"/>
</root>'
declare @notesTable as table (
CreationDate datetime,
Note varchar(max),
UserID int
)
INSERT INTO @notesTable (CreationDate
,Note
,UserID)
SELECT col.value('(@CreationDate)[1]', 'datetime') AS CreationDate
,col.value('(@Note)[1]', 'varchar(max)') AS Note
,col.value('(@UserID)[1]', 'int') AS UserID
FROM @NotesXml.nodes('//Notes') tab(col)
select * from @notesTable
/* Output:
CreationDate Note UserID
----------------------- -------------------- -----------
2015-01-18 00:00:00.000 Note 1 10
2015-01-18 00:00:00.000 Note 2 20
*/
@fcmendoza
Copy link
Author

If Notes is empty we'll get one record with null values

declare @NotesXml xml = 
'<root>
    <Notes />
</root>'

declare @notesTable as table (
    CreationDate datetime,
    Note         varchar(max),
    UserID       int
)

INSERT INTO @notesTable (CreationDate
                          ,Note
                          ,UserID)
SELECT   col.value('(@CreationDate)[1]',  'datetime')     AS CreationDate
        ,col.value('(@Note)[1]',          'varchar(max)') AS Note
        ,col.value('(@UserID)[1]',        'int')          AS UserID
FROM @NotesXml.nodes('//Notes') tab(col)

select * from @notesTable

/*
CreationDate            Note     UserID
----------------------- -------- -----------
NULL                    NULL     NULL
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment