Introduction
This is just a simple article to store any file format into a SQL server database.
Background
Recently I completed a project where I need to store various files, i.e. Microsoft Office file formats, PDF, Images, etc.). When I started writing code, I wrote a function to store binary, after that I thought why not use direct bulk insert from a StoredProcedure.
Using the Code
I am going to discuss the ways in which you can directly store binary data into a SQL table by using a simple stored procedure as given below:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spStoreBinaryFiles]
@FILE_PATH VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @FILE_LENGTH BIGINT
DECLARE @FILE_DATA VARBINARY(MAX)
DECLARE @FILE_NAME VARCHAR(100)
DECLARE @DOCUMENT_NAME VARCHAR(100)
DECLARE @DOCUMENT_NATURE VARCHAR(5)
DECLARE @VAL1 VARCHAR(100)
DECLARE @VAL2 VARCHAR(100)
DECLARE curDOCUMENTS CURSOR FOR SELECT * FROM dbo.SPLIT ( ';', @FILE_PATH )
OPEN curDOCUMENTS
FETCH NEXT FROM curDOCUMENTS
INTO @VAL1,@VAL2
WHILE @@FETCH_STATUS = 0
BEGIN
IF OBJECT_ID('#ORStable') IS NULL
BEGIN
CREATE TABLE #ORStable _
(Length BIGINT, vDocument VARBINARY(MAX))
DECLARE @SQL_QUERY NVARCHAR(1000)
SET @SQL_QUERY= '
INSERT INTO #ORStable
SELECT len(bulkcolumn), *
FROM OPENROWSET(BULK '''+@VAL2+''', _
SINGLE_BLOB) AS BinaryData'
exec SP_executesql @SQL_QUERY
END
EXEC dbo.spGetDocumentNature @VAL2, @DOCUMENT_NATURE OUTPUT
EXEC dbo.spGetDocumentName @VAL2, @DOCUMENT_NAME OUTPUT
SELECT TOP 1 @FILE_LENGTH = Length, @FILE_DATA = vDocument FROM #ORStable
INSERT INTO dbo.tblBinaryFiles
(
[File]
,[Path]
,[Ext]
,[Size]
,[Binary]
)
VALUES(
@DOCUMENT_NAME
,@VAL2
,@DOCUMENT_NATURE
,@FILE_LENGTH
,@FILE_DATA
)
DROP TABLE dbo.#ORStable
FETCH NEXT FROM curDOCUMENTS
INTO @VAL1,@VAL2
END
CLOSE curDOCUMENTS
DEALLOCATE curDOCUMENTS
END
OPENROWSET: Includes all connection information necessary to access remote data from an OLE DB data source. This method is an alternative to accessing tables in a linked server and is a one-time, ad hoc method of connecting and accessing remote data using OLE DB. The OPENROWSET function can be referenced in the FROM clause of a query as though it is a table name. The OPENROWSET function can also be referenced as the target table of an INSERT, UPDATE, or DELETE statement, subject to the capabilities of the OLE DB provider. Although the query may return multiple result sets, OPENROWSET returns only the first one.
Binary Large Objects (BLOBs): BLOB data type to store any data that a program can generate: graphic images, satellite images, video clips, audio clips, ...
BulkColumn: The BulkColumn referenced in the query represents the varbinary value to be inserted.
Sample Bulk Insert SQL Statement
DECLARE @SQL_QUERY NVARCHAR(1000)
SET @SQL_QUERY= '
INSERT INTO #ORStable
SELECT len(bulkcolumn), *
FROM OPENROWSET(BULK '''+@VAL2+''', _
SINGLE_BLOB) AS BinaryData'
exec SP_executesql @SQL_QUERY
I wrote some other storedProcedure to get file name, file nature and a function for splitting the files path. I did not include this code because I do not want to lose focus on the main objective of this article. I hope that it will be helpful to you. Enjoy.
Points of Interest
If you use any network path, please confirm that your SQL login user is permitted to perform bulk load on the Operating System.
He is the founder & CEO of MNH Technologies and working for urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc. He has over ten years of professional experiences in design and developing Client-Server, Multi-Tier, Database, Web based business software solutions, Enterprise Applications, API, WebAPI, Google Analytics implementation, Add-In, Documentation & Technical Writing etc for Windows / Mac using Microsoft SQL Server, Oracle, MySql, PS, C#, VB.NET, ASP.NET, PHP, RoR, Visual Basic etc. He has also more than two years experience in Mobile-VAS (Platform Development).
He worked for various software development & technology consulting. His core focus on technologies to create dynamic data-driven systems that add value to your business and dynamic technology consulting that builds advanced solutions for the industries across the various vertices.
He also work as a Solution Architect at Dhrupadi Techno Consortium Limited (DTCL) and responsible for analyzing business requirements and offered optimum solutions (multiple options), which would address all current requirements, provide flexibility for future growth and allow smooth transition between old system and new system.
He graduated with honors from The University of Asia Pacific, in Computer Science and Engineering. He was awarded as “Most Valuable Professional” (MVP) at 2010 and 2011 by CodeProject.com and also selected as a Mentor of CodeProject.com
Specialties: Software Development Management, System Integration, Data Warehouse Architecture, Virtualization.