sql server - Is there a better way to check the database for a unique value that works for both update and insert then below -


if exists(select * mytable (nolock) mytable.recordid <> @recordid , mytable.uniquecolumn = @uniquevalue)         begin             select 1         end         else         begin             select 0         end  

note: use nolock checks pending inserts , update (i.e update / changing uniquecolumn)

note: use "if exists(" stops search after finding first match

note: use "mytable.recordid <> @recordid" not find match.

note: if inserting recordid negative 1 or zero.

don't know if it's "better", it's more to-the-point:

select   case      when       exists ( select * ... ... )     1      else 0    end isthereornot 

...and can used other expressions (if need 'em).

note: select * appropriate existence checks, , nolock isn't going change - there's implicit transaction scope of select.

i think it's better (easier use results consumers) if name columns (isthereornot in example)


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -