T-SQL Tutorial

SQL Server IMAGE


In SQL Server, the IMAGE data type is used to store binary large object (BLOB) data such as graphics, images, documents, and other multimedia files. The IMAGE data type can store up to 2^31-1 bytes (or 2 GB) of data.


Example

When creating a table in SQL Server, you can use the IMAGE data type to define a column that will store binary data. For example, the following SQL statement creates a table called "MyTable" with an IMAGE column called "MyImage":

CREATE TABLE MyTable
(
ID INT PRIMARY KEY,
MyImage IMAGE
);


Once you have created a table with an IMAGE column, you can insert data into it using the INSERT statement. The following SQL statement inserts a binary image file into the "MyTable" table:

INSERT INTO MyTable (ID, MyImage)
SELECT 1, BulkColumn
FROM OPENROWSET(BULK 'C:\Images\MyImage.jpg', SINGLE_BLOB) AS MyImage

In this example, the OPENROWSET function is used to read the binary data from the "MyImage.jpg" file and insert it into the "MyImage" column of the "MyTable" table.

You can also retrieve data from an IMAGE column using the SELECT statement. The following SQL statement selects the binary data from the "MyImage" column of the "MyTable" table and saves it to a file:

SELECT MyImage FROM MyTable WHERE ID = 1
INTO OUTFILE 'C:\Images\MyImage.jpg'

In this example, the SELECT statement is used to retrieve the binary data from the "MyImage" column of the "MyTable" table where the "ID" column equals 1. The INTO OUTFILE clause is used to save the binary data to the "MyImage.jpg" file.

It's important to note that the IMAGE data type is deprecated in SQL Server 2005 and later versions, and Microsoft recommends using the VARBINARY(MAX) data type instead. The VARBINARY(MAX) data type has similar functionality to the IMAGE data type, but it allows for more efficient storage and retrieval of large binary objects.