T-SQL writing a blob to an external file

Having just figured out how to use OPENROWSET(BULK '...', SINGLE_BLOB) to read binary data from the file system into my SQL Server database, I now need to do the opposite:

Given an "image" type column in a table, I need T-SQL script to write this to a file somewhere on the file system. Again, ideally as NATIVE as possible.

(dang - why are examples of this so hard to find?)

So imagine your select statement to get the blob is

SELECT [data] from [dbo].[blobtable] where [id] = 5

the [data] happens to represent a JPG, so what I need is a wee bit o' T-SQL code that will write [data] out of the above select to 'C:\test.jpg'

many thanks
Who is Participating?
RiteshShahConnect With a Mentor Commented:
look at example in below link, there is a way to store image file in table (in blog article) and retrieve it back to file system in SQL Server itself (in comment given by the reader of blog).


Guy Hengel [angelIII / a3]Billing EngineerCommented:
there are some methods:

note: the methods all write TEXT, however the ones with vbscript or sp_oaxxxx methods should be easily modifiable to write binary data.
WernerVonBraunAuthor Commented:

I'm not sure it would be easy to modify them to write binary data. The only way I can imagine that would work is by using an ADODB.Stream - however in that case I would at some stage need to store the data locally in a variable of a binary type, and SQL Server dinnae like that?
WernerVonBraunAuthor Commented:
damn. It involves invoking an external .exe but at least it's "native":

bcp "SELECT BULKCOLUMN from OpenRowSet(BULK 'somefile', SINGLE_BLOB) DMSData" queryout yetanotherfile -U someusername -P itspassword -n
WernerVonBraunAuthor Commented:
obviously instead of the OpenRowSet I used above you can select a blob from another table
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.