Hola Victor Hugo.
Uso Sql Server 2012 Expressy lo hago de la siguiente forma.
Tengo un SP que surte de secuencias algo muy parecido a
Números conecutivos para nuetras tablasALTER PROCEDURE [App].[SecuenciaSimpleSec_spUI] @iKey int, @cDescripcion nVarChar(50) = NULL, @iKeyNext INT OUTPUT
AS
SET NOCOUNT ON
Begin Try
DECLARE @R TABLE (
iSecId int NOT NULL PRIMARY KEY,
iSecuencia INT NOT NULL CHECK (iSecuencia > 0)
);
INSERT INTO @R (iSecId, iSecuencia)
SELECT
z.iSecId, z.iSecuencia
FROM
(
MERGE App.SecuenciaSimple WITH (HOLDLOCK) AS T
USING (SELECT @iKey, @cDescripcion) AS S (iKey, cDescripcion)
ON T.iSecId = S.iKey
WHEN MATCHED THEN
UPDATE SET iSecuencia = iSecuencia + 1
WHEN NOT MATCHED THEN
INSERT (iSecId, cDescripcion, iSecuencia)
VALUES (S.iKey, S.cDescripcion, 1)
OUTPUT
$ACTION AS [action], INSERTED.iSecId, INSERTED.iSecuencia
) AS z;
SELECT @iKeyNext = iSecuencia FROM @R WHERE iSecId = @iKey;
End try
Begin Catch
Throw;
end catch
Como ejemplo SP para crear Paises donde utilizo el sp App.SecuenciaSimpleSec_spUI
CREATE Procedure [App].[Pais_spI] @Nombre nVarchar(50), @cAbr nVarchar(3), @iKeySec Int, @iPaisId smallint Out
As
Set Nocount On;
Begin Try
Begin Transaction
Exec App.SecuenciaSimpleSec_spUI @iKeySec, 'Pais', @iKeyNext = @iPaisId Out
INSERT INTO App.Pais
(iPaisId, cNombre, cAbr, iDBAudId)
VALUES
(@iPaisId, @Nombre, @cAbr, @iDBAudId)
Commit Transaction
End try
Begin Catch
if @@TRANCOUNT > 0
Rollback Transaction;
Throw;
end Catch
El truco este en el hint del sp SecuenciaSimpleSec_spUI, es decir en:
MERGE App.SecuenciaSimple
WITH (HOLDLOCK) AS T
-
HOLDLOCK Equivalente a SERIALIZABLE
Espero te sea de ayuda.
Saludos.
Mauricio