sql >> Base de Datos >  >> RDS >> Sqlserver

Soluciones para INSERTAR O ACTUALIZAR en SQL Server

no te olvides de las transacciones. El rendimiento es bueno, pero el enfoque simple (SI EXISTE...) es muy peligroso.
Cuando varios subprocesos intentan realizar Insertar o actualizar, puede obtener fácilmente una violación de la clave principal.

Las soluciones proporcionadas por @Beau Crawford y @Esteban muestran una idea general pero son propensas a errores.

Para evitar interbloqueos y violaciones de PK, puede usar algo como esto:

begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
   update table set ...
   where key = @key
end
else
begin
   insert into table (key, ...)
   values (@key, ...)
end
commit tran

o

begin tran
   update table with (serializable) set ...
   where key = @key

   if @@rowcount = 0
   begin
      insert into table (key, ...) values (@key,..)
   end
commit tran