Click here to Skip to main content
13,248,562 members (74,836 online)
Click here to Skip to main content
Add your own
alternative version

Stats

154.1K views
6.1K downloads
62 bookmarked
Posted 22 May 2009

How To Store Any File into SQL Database

, 22 May 2009
Rate this:
Please Sign up or sign in to vote.
An easy technique to store any file into SQL database

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

-- =============================================
-- Author:		Author,,Md. Marufuzzaman
-- Create date: 
-- Description:	Description,, Insert the Binary data 
-- =============================================
-- EXEC dbo.spStoreBinaryFiles 'C:\eFaxFiles\eFaxPromo.pdf;D:\eFaxFiles\eFaxPromo.pdf;'
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

--Here variable VAL2 contains the single file path information.
--Example VAL2 = "\\192.168.1.1\myFiles\myFile.pdf"
--        VAL2 = "C:\myFiles\myFile.pdf" 

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Md. Marufuzzaman
Architect
Bangladesh Bangladesh
A well experienced leader with successful track record of software development, product innovations, brand management and corporate communication etc. Some successful product innovations have also achieved and awards “Most Valuable Professional” (MVP) at 2010 and 2011 by codeproject.com and also selected as a mentor of codeproject.com. Published over 100 technical articles in various software development resource sites (i.e., codeprojetc.com, Microsoft MSDN, and IEEE & IBM (In progress)) and various IT Forums, Blogs etc.

Over twelve years of professional experiences in ICT field having extensive experience in formulating corporate vision and long term strategy. Leading development related functions including design, development, services, data management and analytics, customer experience management, content services, digital analytics and optimization.I have also more than two years’ of strong experience in mobile-VAS (platform development).

An individual with results-driven approach and relentless in pursuit of excellence from a business and organizational standpoint.Honest, believes in transparency, commitment and teamwork.

Expertise: Software/Solution Architect, Research, MIS, Data Analytics, Data Mining, BI, SaaS platform base application development, Large scale Win32 Form/Web based business software solutions, Security, Enterprise applications development, integration, etc.

Technologies/Tools: Microsoft.Net version 05/08/10/12, Microsoft SQL Server version 7/2K/05/08/12/14 , Oracle version 10/11, MySql version 5.1, 5.5, 5.7, Visual C#, VB.NET, ASP.NET, API, MVC, WebAPI , WPF, WCF, PHP, Microsoft Power BI, SPSS, PS2, R, Add-In, Visual Basic etc.

.Net UI component: Telerik, DevExpress, Ext.Net.
Scripting language: JavaScript, AngularJS, node.JS.
Source control / Subversion: Git,SVN.
Development methodologies: Agile,RAD.
Project Management / Issues Tracking Tools: JIRA, ClockingIt.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
hassan wasef29-Mar-13 11:03
memberhassan wasef29-Mar-13 11:03 
GeneralRe: My vote of 5 Pin
Md. Marufuzzaman29-Mar-13 11:17
mentorMd. Marufuzzaman29-Mar-13 11:17 
Thanks

Thanks
Md. <b style="color: #FF9900"> M</b>arufuzzaman
<hr></hr>
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.
QuestionThis works! WS2k8, SqlSrvr2k8, .pdf as input ... Pin
RedDK9-Oct-12 11:39
memberRedDK9-Oct-12 11:39 
GeneralMy vote of 5 Pin
trivedijignesh7-Mar-12 5:48
membertrivedijignesh7-Mar-12 5:48 
QuestionRetrieval Pin
nick hull16-Feb-12 11:06
membernick hull16-Feb-12 11:06 
GeneralMy vote of 5 Pin
Rashed_7-Feb-12 19:52
memberRashed_7-Feb-12 19:52 
QuestionDatabase Restore from Backup Pin
abigio19-Aug-11 6:08
memberabigio19-Aug-11 6:08 
AnswerRe: Database Restore from Backup Pin
Md. Marufuzzaman19-Aug-11 8:21
mvpMd. Marufuzzaman19-Aug-11 8:21 
GeneralRe: Database Restore from Backup Pin
abigio19-Aug-11 10:13
memberabigio19-Aug-11 10:13 
QuestionRe: Database Restore from Backup Pin
emrdesign25-Jan-12 23:17
memberemrdesign25-Jan-12 23:17 
AnswerRe: Database Restore from Backup Pin
miamikk1-Aug-12 14:01
membermiamikk1-Aug-12 14:01 
GeneralRe: Database Restore from Backup Pin
Md. Marufuzzaman6-Aug-12 11:23
mentorMd. Marufuzzaman6-Aug-12 11:23 
GeneralOff topic but relative question ... storeMyFiles.bak Pin
RedDK25-May-11 9:12
memberRedDK25-May-11 9:12 
GeneralRe: Off topic but relative question ... storeMyFiles.bak Pin
Md. Marufuzzaman25-May-11 13:47
mvpMd. Marufuzzaman25-May-11 13:47 
GeneralThanks Message Pin
D.Sendhilkumar1-Apr-10 22:17
memberD.Sendhilkumar1-Apr-10 22:17 
GeneralRe: Thanks Message Pin
Md. Marufuzzaman2-Apr-10 6:08
mvpMd. Marufuzzaman2-Apr-10 6:08 
GeneralMy vote of 1 Pin
VMykyt14-Jul-09 0:31
memberVMykyt14-Jul-09 0:31 
GeneralMy vote of 1 Pin
Dave Kreskowiak23-May-09 6:57
mvpDave Kreskowiak23-May-09 6:57 
GeneralRe: My vote of 1 Pin
Md. Marufuzzaman26-May-09 19:43
memberMd. Marufuzzaman26-May-09 19:43 
GeneralRe: My vote of 1 Pin
Member 274379428-Jul-09 5:56
memberMember 274379428-Jul-09 5:56 
GeneralRe: My vote of 1 Pin
Md. Marufuzzaman28-Jul-09 8:12
groupMd. Marufuzzaman28-Jul-09 8:12 
GeneralConsidering in loca area network , It’s cool. Pin
Taslima Bagum22-May-09 20:26
memberTaslima Bagum22-May-09 20:26 
GeneralRe: Considering in loca area network , It’s cool. Pin
Md. Marufuzzaman5-Jul-09 19:31
memberMd. Marufuzzaman5-Jul-09 19:31 
GeneralWorking for small file. Pin
BDMaruf22-May-09 19:48
memberBDMaruf22-May-09 19:48 
GeneralThis wont work Pin
icestatue22-May-09 6:39
membericestatue22-May-09 6:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 23 May 2009
Article Copyright 2009 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid