如何确定表中是否已存在具有特定IMAGE数据类型的记录? [英] How to determine whether a record with specific IMAGE data type already exists in the table?
问题描述
最有效的方法是什么?我正在寻找一个存储过程,向其返回一个新ID或带有该图像的记录的ID。图片最大可能为15-20MB,但大多数情况下为0.5-2MB。
感谢帮助,
最有效的方法
我能想到的最有效的方法是使用持久化的和输出并带有此答案的技巧 SQL MERGE语句中的UPDATE-no-op 由 Andriy M 提供。
创建过程Images_Add
@NewImage varbinary(max)
作为
声明@dummy int
将图像合并为T
在T.ImgHash上使用(选择@NewImage,hashbytes('MD5',@NewImage))作为S(Img,ImgHash)
=不匹配时为S.ImgHash
然后
匹配时插入(Img)值(S.Img)
然后
更新s et @dummy = 0
输出已插入。
What is the most effective way to do that? I'm looking for a stored procedure, with returns me a new ID or an ID of the record with that image. Image could be up to 15-20MB, but mostly it will be 0,5-2MB.
Thanks for help,
most effective way
The most effective way I can think of is to use a persisted computed column for a hash value of the image column. Use hashbytes to calculate the hash and add a unique constraint on the computed column.
Table definition:
create table Images
(
ID int identity primary key,
Img varbinary(max),
ImgHash as convert(varbinary(16), hashbytes('MD5', Img)) persisted unique
)
Sample code against Images table:
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)
The unique constraint creates an index that will be used in the query.
Your SP to add an image could look like this using merge and output with a trick from this answer UPDATE-no-op in SQL MERGE statement provided by 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;
这篇关于如何确定表中是否已存在具有特定IMAGE数据类型的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!