I have a file that is structured like so:
<?xml version="1.0" encoding="UTF-8"?>
<EventSchedule>
<Event Uid="2" Type="Main Event">
<IsFixed>True</IsFixed>
<EventKind>MainEvent</EventKind>
<Fields>
<Parameter Name="Type" Value="TV_Show"/>
<Parameter Name="Name" Value="The Muppets"/>
<Parameter Name="Duration" Value="00:30:00"/>
</Fields>
</Event>
<Event>
...and so on
</Event>
</EventSchedule>
I'm not entirely sure if it is valid XML, however I need to import it into SQL Server but everything I try doesn't seem to work.
Please could anyone point me in the right direction either with some example code or a recommendation on which method to use?
I'd ideally like to get the raw data into a flat table, along the lines of:
Name | Type | Duration | EventKind
The Muppets | TV_Show | 00:30:00 | MainEvent
Finally this is coming from fairly large files and I will need to import the regularly.
Thanks, pugu
6条答案
按热度按时间kxeu7u2r1#
Try this:
Gives me an output of:
And of course, you can easily do an
to insert that data into a relational table.
Update: assuming you have your XML in files - you can use this code to load the XML file into an
XML
variable in SQL Server:and then use the above code snippet to parse the XML.
Update #2: if you need the parameters, too - use this XQuery statement:
Results in:
sf6xfgos2#
You do it by creating a destination table, then a schema mapping file that maps the xml elements to table columns.
Yours might look a bit like this:
and this:
Then you can load your XML into your table using the XML bulk loader.
http://support.microsoft.com/kb/316005
vpfxa7rd3#
If you need to do it without XML variable (from string in table-valued function)
Or from file:
e.g.
So you can have a function like
suzh9iv84#
If you're trying to import your XML as a "pure" XML field you should create a table like this (obviously with many other fields as you want):
Then you can easily insert your XML as a string:
Then to query start from MSDN t-SQL XML
If you prefer store it as string use a varchar(max) in place of [XML] column type and the same insert. But if you like to query easily I suggest [XML] type. With the flat string approach you need a lot of work unless you will implement some application code to parse it and store in a flat table. A good approach could be an XML storage in a "compress" TABLE and a VIEW for data retrieve with the flat field disposition.
omhiaaxx5#
How to load the below XML data into the SQL
t98cgbkg6#
Much faster is the use of OPENXML. Logic taken from sqlhack.com