SERIALIZABLE è un livello di isolamento per i lock, non un semaphore.
In questo caso non funziona: tutto ciò che ottieni è mantenere un lock di lettura fino alla fine della transazione, che non impedisce a un altro processo di entrare nel codice e leggere.
Devi usare sp_getapplock in modalità Transaction. Puoi configurarlo perché attenda, fallisca immediatamente e così via: la scelta è tua.
Questo si basa sul mio template di Nested stored procedures containing TRY CATCH ROLLBACK pattern?.
ALTER PROCEDURE get_code
AS
SET XACT_ABORT, NOCOUNT ON
DECLARE @starttrancount int, @result int;
BEGIN TRY
SELECT @starttrancount = @@TRANCOUNT
IF @starttrancount = 0
BEGIN TRANSACTION
EXEC @result = sp_getapplock 'get_code', 'Exclusive', 'Transaction', 0
IF @result < 0
RAISERROR('INFO: One at a time please`!', 16, 1);
[...Perform work...]
IF @starttrancount = 0
COMMIT TRANSACTION
ELSE
EXEC sp_releaseapplock 'get_code';
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 AND @starttrancount = 0
ROLLBACK TRANSACTION
RAISERROR [rethrow caught error using @ErrorNumber, @ErrorMessage, etc]
END CATCH
GO
Come funziona
sp_getapplock con @LockMode = 'Exclusive' e @LockOwner = 'Transaction' acquisisce un lock a livello di risorsa applicativa, che viene rilasciato automaticamente al commit o al rollback. Il quarto parametro a 0 imposta un timeout di zero, quindi la chiamata fallisce subito se la risorsa è occupata, restituendo un valore negativo.
Il lock è a livello di istanza: se hai più database che devono coordinarsi separatamente, passa @LockOwner = 'Session' e includi il nome del database nella risorsa, per esempio 'MyDb.get_code'.