Insert Images into SQL Server

Inserting images into SQL Server Tables is one of the most Frequent Questions in forums. The easiest method to save images into a table is to execute OPENROWSET command with the BULK and SINGLE_BLOB option. First, let me create a new Table to save the photos.

-- Query to Insert Images into SQL Server is: 

CREATE TABLE SaveFiles
(
    FileID INT IDENTITY(1,1) NOT NULL,
    Name NVARCHAR(50) NOT NULL,
    Files VARBINARY(MAX) NOT NULL
)

Run the above create table query

Messages
--------
Command(s) completed successfully.

Insert Images into SQL Server Example

In this example, we write a Server Query to insert an image into the table using the OPENROWSET

-- Query to Insert Images into SQL Server is: 


INSERT INTO [dbo].[SaveFiles] (Name, Files)
SELECT 'Home Page 2', 
	BulkColumn FROM OPENROWSET(BULK N'D:\LOGOS\Home Page.png', SINGLE_BLOB) image;
Insert Images into SQL Server 2

You can also write the above frequently asked query (SQL Insert Image) differently:

-- Query to Insert Images into SQL Server is: 

INSERT INTO [dbo].[SaveFiles] (Name, Files)
SELECT 'Home Page 2', 
	* FROM OPENROWSET(BULK N'D:\LOGOS\Home Page.png', SINGLE_BLOB) image;
Insert Images into SQL Server 3

Let me open the SaveFile table to check whether we successfully inserted two images into the table or not.

Insert Images into SQL Server 4

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.

Comments are closed.