简体   繁体   中英

Importing images in SQL Server 2005

Dear All, I have another issue. I have in the SQL table Employees. This table has lot of details but I was missing images or photos.

So i managed to take all pictures for all employees but I have the pictures in the folder. Each picture is named like an Employee_id which matches the record in the table. How do I import images into SQL Employee table to match the name of the picture to Employee_id.

Any ideas?

A cursor and a bit of dynamic SQL should do the trick.

declare EmployeeCursor cursor fast_forward for
    select Employee_id
        from Employee

declare @sql nvarchar(4000)
declare @Employee_id int

open EmployeeCursor      

while (1=1) begin
    fetch next from EmployeeCursor into @Employee_id

    if @@FETCH_STATUS<>0 break

    set @sql = N'UPDATE Employee
                     SET ImageColumn = 
                         (SELECT * FROM 
                              OPENROWSET(BULK N''c:\images\' + cast(@Employee_id as nvarchar(10)) + N'.jpg'', SINGLE_BLOB) AS img)
                              WHERE Employee_id = ' + cast(@Employee_id as nvarchar(10))

    exec(@sql)   
end /* while */

close EmployeeCursor
deallocate EmployeeCursor

You can use OPENROWSET BULK to open an external file as a value for an INSERT or UPDATE .

Here's an example:

UPDATE Employees SET Picture=(SELECT * FROM OPENROWSET(BULK 'c:\temp\1234.jpg', SINGLE_BLOB) as Picture) WHERE Employee_id=1234

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM