Hi everyone, I have been asked to investigate storing Excel files in Sql Server as a BLOB. These files could be of any size and I will not know what headers they will have beforehand. They could have multiple sheets per Excel. We may need to re-constitute the file/s promptly at any stage.
I haven't used blobs before so in an effort to get my head around this I created a test database called: "Scratch" and a table inside it called: "TestBlob". Here is the table structure:
CREATE TABLE dbo.TestBlob -- Table where BLOB will be stored
(
tbId int IDENTITY(1,1) NOT NULL,
tbName varchar (50) NULL,
tbDesc varchar (100) NULL,
tbBin varbinary (max) NULL
)
I was able to load a simple Excel file (literally 1 column)
Insert TestBlob(tbName, tbDesc, tbBin) Select 'C:\Test_Excel_Files\simple1.xlsx','Files',
BulkColumn from Openrowset( Bulk 'C:\Test_Excel_Files\simple 1.xlsx', Single_Blob) as tb
Extracting it has proved to be more problematic. I used a BCP command I found online and modified acordingly. It needs a format file also (which I called simple.fmt).
Here is the code I used:
DECLARE @sqlExtract VARCHAR(1000);
SET @sqlExtract = 'bcp "SELECT tbBin FROM Scratch.dbo.TestBlob where tbId = 1 " QUERYOUT C:\BlobTestOut\simple1Out.xlsx -T -f "C:\BlobTestOut\Formatfile\simple1.fmt" -S ' + @@SERVERNAME;
EXEC master.dbo.xp_cmdshell @sqlExtract;
The format file is below:
<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<FIELD ID="1" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="7"/>
</RECORD>
<ROW>
<COLUMN SOURCE="1" NAME="Salary" xsi:type="SQLSMALLINT"/>
</ROW>
</BCPFORMAT>
It produced an output but when I try to open it I get the error message: "Excel cannot open the file because the file format or file extension is not valid"
I would appreciate if you could indicate where I am going wrong or perhaps a better approach. I am conscious of the fact that in the future I will not know the header format of the Excel files so a format file approach could be useless and hence is there a better extract command?
Comments/suggestions/guidance greatly appreciated...
J.