Insert Images into SQL Server

Inserting images into SQL Server Tables is one of the most Frequent Questions in SQL Server 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: 
USE [SQLTEST]
GO
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: 
USE [SQLTEST]
GO

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: 
USE [SQLTEST]
GO

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

Comments are closed.