Created
February 26, 2020 09:01
-
-
Save davidsheardown/8d1510b35ed00d55cea6970ccf10af80 to your computer and use it in GitHub Desktop.
SQL blob/varbinary to file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
To directly add a file to blob | |
(this example was a 120mb file) | |
*/ | |
INSERT INTO [dbo].[TableWithBlob](Id, ProductId, Filename, [ActualFile]) | |
SELECT 1,1,'filename',BulkColumn | |
FROM OPENROWSET(BULK N'c:\clients\test.exe', SINGLE_BLOB) as AnyAliasFieldYouLike | |
/* | |
To re-materialise the file (whatever type it is) you might need to execute the first set of | |
SQL config options | |
*/ | |
sp_configure 'show advanced options', 1; | |
GO | |
RECONFIGURE; | |
GO | |
sp_configure 'Ole Automation Procedures', 1; | |
GO | |
RECONFIGURE; | |
GO | |
-- Now the query that extracts the blob to a file | |
-- ** SHOULD PROVIDE THE FULL DB/SCHEMA/TABLE TOO | |
declare @init int | |
declare @file varbinary(max) = (select [BlobField] from [TheDatabase].[dbo].[TableWithBlob] where Id=4) | |
declare @filepath nvarchar(4000) = N'c:\clients\sqltest.pdf' | |
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; | |
EXEC sp_OASetProperty @init, 'Type', 1; | |
EXEC sp_OAMethod @init, 'Open'; | |
EXEC sp_OAMethod @init, 'Write', NULL, @file; | |
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; | |
EXEC sp_OAMethod @init, 'Close'; | |
EXEC sp_OADestroy @init; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment