Skip to content Skip to sidebar Skip to footer

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 mo

Solution 1:

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.

enter image description here

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;  

Post a Comment for "How To Determine Whether A Record With Specific IMAGE Data Type Already Exists In The Table?"