Importing images in SQL Server 2005

2019-07-19 15:38发布

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?

2条回答
Luminary・发光体
2楼-- · 2019-07-19 16:08

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
查看更多
冷血范
3楼-- · 2019-07-19 16:19

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
查看更多
登录 后发表回答