开发者

Importing images in SQL Server 2005

开发者 https://www.devze.com 2023-01-20 07:12 出处:网络
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.

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 Emplo开发者_JAVA技巧yee_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
0

精彩评论

暂无评论...
验证码 换一张
取 消