Esta é uma procedure de exemplo, onde um flag (i, u , d) determina a operaçãoque será executada.


CREATE PROCEDURE sp_malotes
 @codmalote int,
 @numerolacre varchar(15), 
 @origem varchar(50),
 @destino varchar(50), 
 @operacao nchar(1),
 @novocodigo int output,
 @retorno nvarchar(50) output
AS
if lower(@operacao) = 'i' -- inserir um registro
begin 
 if exists(select numerolacre from tb_malote where numerolacre = @numerolacre) 
 begin
 select @retorno = 'Numero lacre JÁ EXISTENTE.'
 return (@retorno)
 end
 else 
 begin
 select @retorno = ''
 begin transaction
 insert into tb_malote 
 (numerolacre, origem, destino )
 values
 (@numerolacre, @origem, @destino )
 set @novocodigo = @@identity 
 --variavel global do SQL SERVER que retorna o ultimo valor de um campo(identity)
end
end
else
if lower(@operacao) = 'u' -- alterar um registro
begin
 select @retorno = '' 
 begin transaction
 update tb_malote set
 numerolacre = @numerolacre,
 origem = @origem,
 destino = @destino 
 where codmalote = @codmalote
end
else
if lower(@operacao) = 'd' -- excluir um registro
 begin 
 select @retorno = '' 
 begin transaction
 delete from tb_malote
 where codmalote = @codmalote
 end
if @@error <> 0 
begin
 rollback transaction
 return(1)
end
else
begin
 commit transaction
 return(0)
end