Wednesday, 29 July 2009

Importing Files to Variables

There is functionality with SQLServer 2005 to import files directly from disk into variables or tables.

This can be particularly useful for importing an xml document, or even an image file.

i.e. Text, Unicode text and binary data can be imported from a file using this method


Example 1 - Importing an xml document

DECLARE @xml xml

SELECT @xml = BulkColumn
FROM OPENROWSET(BULK N'c:\temp\Sample.xml',SINGLE_BLOB) AS a

SELECT @xml


Example 2 - Importing a text file

DECLARE @text VARCHAR(max)

SELECT @text = BulkColumn
FROM OPENROWSET(BULK N'c:\temp\Sample.xml',SINGLE_CLOB) AS a

SELECT @text



Example 3 - Importing an image

DECLARE @myImage VARBINARY(MAX)

SELECT @myImage = BulkColumn
FROM OPENROWSET(BULK N'c:\temp\test.jpg',SINGLE_BLOB) AS a

You can then write the binary data to a table


NB To import unicode text, you would use SINGLE_NCLOB into an NVARCHAR(MAX) data type

These are documented in Books On Line, so go take a look...