我目前有一个表格列(id#(int),picture(varbinary(MAX)),我的硬盘上有一个文件夹,里面有大量图片。文件夹中的图片由'id'我希望在我的表格中将它们匹配。我该怎么做?
Example:
Table Row: id=25166, picture=NULL
25166.jpg
答案 0 :(得分:1)
如果您需要一个仅使用SQL checkout的示例:
它使用游标循环遍历不包含图像数据的每一行,并且对于找到的每一行,使用OPENROWSET BULK提供程序加载文件。
CREATE TABLE ImageStore
(
id INT,
picture VARBINARY(MAX) NULL
)
GO
INSERT INTO ImageStore (id) VALUES(25166)
INSERT INTO ImageStore (id) VALUES(25167)
DECLARE @id INT
DECLARE image_cursor CURSOR FOR
SELECT id FROM ImageStore WHERE picture IS NULL
OPEN image_cursor;
FETCH NEXT FROM image_cursor
INTO @id;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @sql NVARCHAR(MAX)
DECLARE @imagePath NVARCHAR(255)
SET @imagePath = 'C:\' + RTRIM(LTRIM(STR(@id))) + '.gif'
SET @sql = 'UPDATE ImageStore '
SET @sql = @sql + 'SET picture = (SELECT BulkColumn FROM OPENROWSET( BULK ''' + @imagePath + ''', Single_Blob) AS picture) '
SET @sql = @sql + 'WHERE id = ' + STR(@id)
BEGIN TRY
EXECUTE sp_executesql @sql
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT FROM image_cursor
INTO @id;
END
CLOSE image_cursor;
DEALLOCATE image_cursor;
SELECT * FROM ImageStore
DROP TABLE ImageStore