In this post, we will see how to store BLOB (Binary Large Objects) such as files or images in SQL Server. In versions prior to SQL Server 2005, the image datatype was used to store files or images in a table. From SQL Server 2005 and later versions, the image datatype is replaced with varbinary(max) datatype.
To make it easier to demonstrate, I will show how to save a text file in SQL Server.
Create a text file named ‘test.txt’ in your drive with the following data
1,500
2,1000
3,834
4,578
5,290
Create a table variable with varbinary(max) datatype and insert this text file into the table. We have two options
Option 1 : single_blob
Here’s the same query for you to try out:
declare @file table(file_path varchar(150), file_storage varbinary(max))
insert into @file (file_path, file_storage)
select 'f:\test.txt' ,
* from openrowset(bulk n'f:\test.txt', single_blob) as document
select * from @file
The openrowset function with the bulk option will convert the entire file content to binary values. The option SINGLE_BLOB is used to store the file content as a single row and return a single column rowset.
Note: In order to retrieve the file content, FileStream method should be used in your front end application
Option 2 : single_clob
Here’s the same query for you to try out:
declare @file table(file_path varchar(150), file_storage varchar(max))
insert into @file (file_path, file_storage)
select 'f:\test.txt' ,
* from openrowset(bulk 'f:\test.txt', single_clob) as document
select * from @file
GO
Note that the datatype of the column file_storage is varchar. single_clob option is used to store the file content as characters.
3 comments:
How to store pointer to an image instead of the image itself?
Hi Armaan,
by pointer did you mean the path of the file? If so, use varchar datatype and store the path in the column and store the actual image in the server's directory
ok thank you
Post a Comment