2011-07-24 22 views

回答

1

最有效的方法

我能想到的最有效的方法是使用一個持續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 
) 

示例代碼:

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) 

唯一性約束創建將在查詢中使用的索引。

enter image description here

你的SP添加圖像可能看起來像這樣利用mergeoutput一招從Andriy M提供這個答案UPDATE-no-op in SQL MERGE statement

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; 
+0

謝謝你,我會嘗試,在某一時刻 – Marshall

相關問題