Quick one today:
A few months ago, there was a new requirement to export millions of records in a table column to raw files on a disk. This column contains millions of shopping receipts stored in binary format in database tables. Early on, I stumbled up on a tip that gave me a good idea of how to approach this problem.
This uses T-SQL with help from ‘ OLE Automation Procedures’ to accomplish this task. Towards that, we need to enable ‘Ole Automation Procedures’ advanced options.
--
-- Enable 'Ole Automation Procedures'
--
SELECT * FROM sys.configurations
WHERE name = 'Ole Automation Procedures'
GO
EXEC sp_configure 'SHOW ADVANCED OPTIONS', 1
RECONFIGURE
GO
EXEC sp_configure 'Ole Automation Procedures', 1
RECONFIGURE
GO
EXEC sp_configure 'SHOW ADVANCED OPTIONS', 0
RECONFIGURE
GO
SELECT * FROM sys.configurations
WHERE name = 'Ole Automation Procedures'
GO
asdas
--
-- Code to export VARBINARY into RAW files using TSQL
--
DECLARE @SQLIMG VARCHAR(MAX)
, @IMG_PATH VARBINARY(MAX)
, @TIMESTAMP VARCHAR(MAX)
, @ObjectToken INT
DECLARE IMGPATH CURSOR FAST_FORWARD FOR
SELECT logcontent
FROM dbo.TransactionLog
WHERE EnterpriseID = '423-DZFDSF-23432-254E57A1-45A7-4DBF'
OPEN IMGPATH
FETCH NEXT FROM IMGPATH INTO @IMG_PATH
WHILE @@FETCH_STATUS = 0
BEGIN
--
-- Create unique file name for each row of data
--
SET @TIMESTAMP = 'M:\MSSQL\Hyvee\Receipts_' + replace(replace(replace(replace(convert(varchar,getdate(),121),'-','_'),':','_'),'.','_'),' ','_') + '.ZIP'
-- PRINT @TIMESTAMP
-- PRINT @SQLIMG
--
-- Use Ole Automation to save the contents to a file on disk
--
EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT
EXEC sp_OASetProperty @ObjectToken, 'Type' , 1
EXEC sp_OAMethod @ObjectToken, 'Open'
EXEC sp_OAMethod @ObjectToken, 'Write' , NULL , @IMG_PATH
EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL , @TIMESTAMP , 2
EXEC sp_OAMethod @ObjectToken, 'Close'
EXEC sp_OADestroy @ObjectToken
FETCH NEXT FROM IMGPATH INTO @IMG_PATH
END
CLOSE IMGPATH
DEALLOCATE IMGPATH
GO
OleAutomation Procedures RAW Files
At the end of it, reset the ‘Ole Automation Procedures’ settings.
<pre>--
-- Enable 'Ole Automation Procedures'
--
SELECT * FROM sys.configurations
WHERE name = 'Ole Automation Procedures'
GO
EXEC sp_configure 'SHOW ADVANCED OPTIONS', 1
RECONFIGURE
GO
EXEC sp_configure 'Ole Automation Procedures', 0
RECONFIGURE
GO
EXEC sp_configure 'SHOW ADVANCED OPTIONS', 0
RECONFIGURE
GO
SELECT * FROM sys.configurations
WHERE name = 'Ole Automation Procedures'
GO
Hope this helps,
_Sqltimes
Read Full Post »