Home > SQL Server > Insert or Update a File in Database – SQL Server

Insert or Update a File in Database – SQL Server


Database is a repository for data of various formats. In the past, we use text files to store huge data and technology revolution has changed everything for what we store and How we store data. Big data is a good example. It happened in different forms as punch card, file system, relational database, graph db, NoSQL, NewSQL and etc.

But, in this blog post I am going to show a simple example for storing (insert) and altering (update) a binary image file stored in a table.

Prerequisite

Create a Table

CREATE TABLE [dbo].[Images](
ImageID INT IDENTITY(1,1),
ImageDesc VARCHAR(20) NOT NULL,
[ImageData] VARBINARY(MAX) NOT NULL
) ON [PRIMARY]

Sample Image file – SQL2016.jpg

SQL2016

Insert a record with a Image file

INSERT dbo.[Images]
(ImageDesc, ImageData)
SELECT ‘SQL2016′ AS ImageDesc, * FROM OPENROWSET(BULK N’C:\Test\SQL2016.jpg’, SINGLE_BLOB) AS Img

Update an existing record with Image file

UPDATE dbo.[Images]
SET ImageDesc = ‘SQLServer’
,ImageData = BulkColumn from Openrowset( Bulk ‘C:\Test\SQLServer.jpg’, Single_Blob) as Img
WHERE ImageID = 1

This blog post is for code reference. You can use this code with not restriction.

Advertisements
Categories: SQL Server
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: