How to determine whether a record with specific IMAGE data type already exists in the table?
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 hel开发者_如何学Pythonp,
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;
精彩评论