title: How to save (all) SQL server image datatype to file system with correct file extension
body: <p>I have different types of files in table (txt, doc, jpg, etc) and I want to save them all to my file system. I know how to do it file by file, but it's no use, I have to do a loop that saves all files with right extensions at once. Any advice?</p>
  
  <p>I do it this way now:</p>
  
  <pre><code>DECLARE @ObjectToken INT
  EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT
  EXEC sp_OASetProperty @ObjectToken, 'Type', 1
  EXEC sp_OAMethod @ObjectToken, 'Open'
  EXEC sp_OAMethod @ObjectToken, 'Write', NULL, &lt;this is where binary data goes&gt;
  EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, 'd:/file.txt', 2
  EXEC sp_OAMethod @ObjectToken, 'Close'
  EXEC sp_OADestroy @ObjectToken
  </code></pre>
  
  <p>So, my question would be is there a way to do this for all records (save all files) in db table at once and with setting the correct file extension for every saved file?</p>