【发布时间】:2011-07-24 14:37:32
【问题描述】:
最有效的方法是什么?我正在寻找一个存储过程,它会返回一个新 ID 或带有该图像的记录的 ID。图像可能高达 15-20MB,但大多数情况下它将是 0.5-2MB。
谢谢你的帮助,
【问题讨论】:
标签: database tsql sql-server-2008
最有效的方法是什么?我正在寻找一个存储过程,它会返回一个新 ID 或带有该图像的记录的 ID。图像可能高达 15-20MB,但大多数情况下它将是 0.5-2MB。
谢谢你的帮助,
【问题讨论】:
标签: database tsql sql-server-2008
最有效的方法
我能想到的最有效的方法是使用持久化的computed column 作为图像列的哈希值。使用hashbytes 计算哈希并在计算列上添加unique constraint。
表定义:
create table Images
(
ID int identity primary key,
Img varbinary(max),
ImgHash as convert(varbinary(16), hashbytes('MD5', Img)) persisted unique
)
Images 表的示例代码:
insert into Images values
(convert(varbinary(max), 'Image1')),
(convert(varbinary(max), 'Image2'))
declare @NewImage varbinary(max) = convert(varbinary(max), 'Image2')
select count(*)
from Images
where ImgHash = hashbytes('MD5', @NewImage)
唯一约束创建一个将在查询中使用的索引。
使用merge 和output 使用UPDATE-no-op in SQL MERGE statement 提供的答案UPDATE-no-op in SQL MERGE statement 提供的技巧,您的SP 添加图像可能看起来像这样Andriy M。
create procedure Images_Add
@NewImage varbinary(max)
as
declare @dummy int
merge Images as T
using (select @NewImage, hashbytes('MD5', @NewImage)) as S(Img, ImgHash)
on T.ImgHash = S.ImgHash
when not matched then
insert(Img) values(S.Img)
when matched then
update set @dummy = 0
output inserted.ID;
【讨论】: