October 22, 2007

SQL to import images from folder to table

To import images from a folder into a SQL Server table, you need to store the image data in a column of type VARBINARY(MAX) or IMAGE (though IMAGE is deprecated, it’s still widely used in legacy systems). You can use SQL Server's BULK INSERT command or SQL Server Integration Services (SSIS), but if you're trying to do this directly from a folder using a SQL query, you'll generally need a stored procedure or script that reads the image files from the folder, converts them to binary data, and inserts them into the database.

Here’s an example using T-SQL along with PowerShell or SQL CLR to achieve this. For simplicity, I'll focus on an example using T-SQL with OPENROWSET and the BULK option.

Steps:

  1. Create a table to store the image.
  2. Use OPENROWSET to import the images into the table.

Create the Table

First, create a table with a VARBINARY(MAX) column to store the image data.

CREATE TABLE ImageTable (
ImageID INT IDENTITY(1,1) PRIMARY KEY, ImageData VARBINARY(MAX), FileName NVARCHAR(255) );

Import Image into the Table

You can then use the OPENROWSET function to read the images from a folder and insert them into the table. OPENROWSET is useful for importing data from files.

Example SQL Query to Insert Images

Assuming all the images are in C:\Images\ directory:


DECLARE @FilePath NVARCHAR(4000) DECLARE @FileName NVARCHAR(255) -- Declare the directory where your images are stored SET @FilePath = 'C:\Images\' -- Insert a specific image SET @FileName = 'example.jpg' INSERT INTO ImageTable (ImageData, FileName) SELECT * FROM OPENROWSET(BULK @FilePath + @FileName, SINGLE_BLOB) AS Image

  • OPENROWSET with the BULK option reads the image as a binary large object (BLOB) and returns it in a VARBINARY(MAX) format.
  • SINGLE_BLOB tells SQL Server to read the entire file as a single binary value.
  • The INSERT INTO ImageTable inserts the binary data into the table, along with the image file name.