views:

54

answers:

2

I have several files (they are XML but that's not important) that need to be inserted into an existing SQL table (i.e. I didn't design it.) The table looks like this.

ReportType
  ID (int) <- identity
  Name (varchar(32))
  TransformXSLT (nvarchar(max))

Normally I would do:

INSERT INTO ReportType (Name, TransformXSLT)
VALUES ('template name', '<lots><of><xml><goes><here>...</lots>')

Is there any way to do:

INSERT INTO ReportType (Name, TransformXSLT)
VALUES ('template name', {filename})

I'm using SQL Server Management Studio and Eclipse+Maven to manage the files.

+1  A: 

BULK INSERT or OPENROWSET(BULK…) are the usual options from T-SQL

After comment...

...FROM OPENROWSET(BULK N'C:\Text1.txt', SINGLE_BLOB);

and the "Bulk Exporting or Importing SQLXML Documents" section here

Sorry, I've not actually tried this but MSDN says you can

gbn
Neither option allows me to specify the entire file contents as a single field's data. Unless I miss something?
Chris Nava
@Chris Nava: updated to hopefully be more precise...
gbn
hm.. SINGLE_NCLOB looks promising.. will investigate. "SINGLE_NCLOB - By reading data_file as UNICODE, returns the contents as a single-row, single-column rowset of type nvarchar(max), using the collation of the current database."
Chris Nava
@Chris Nava: the link says to use SINGLE_BLOB for XML..
gbn
OPENROWSET(BULK ...) is the way to go, I just want to warn you about the BOM characters you may have in your file. IS actually quite a tricky enterprise to get the import right, given the presence of BOMs and the `<?xml ... encoding="..."/>` declarations in your file. IF you place a UTF-8 encoded file opened as a CLOB into a NVARCHAR column, the result is invalid XML (the ecoding declared in the body will not match the actual encoding in the media). You must either store the file as XML column, or use VARBINARY(MAX). Don't use NVARCHAR or VARCHAR unless you know *exactly* what you're doing...
Remus Rusanu
A: 

Have you tried using the SQL Server Import and Export Wizard?

Go into SQL Server Management Studio. In Object Explorer, right click the database then Tasks > Import Data....

This will let you import data as a one off exercise, or let you save the resulting SSIS package and re-run it.

Give it a go.

JonPayne