We struggled with this issue for a long time and eventually discovered that when we correct the sequence after it got reset, this would somehow mark it as dirty, causing it to be reset during the next deployment.
It seems to us this is caused by the ALTER statement in the query below:
DECLARE @sequenceNumber AS NVARCHAR(MAX)
DECLARE @sql NVARCHAR(MAX)
SELECT TOP 1 @sequenceNumber = CONVERT(VARCHAR, CAST(SUBSTRING([dossier].[DossierNumber], 6, 4) AS INT) + 1) FROM [Dossier] [dossier] WHERE [dossier].[DossierNumber] LIKE CONCAT(YEAR(GETDATE()), '%') ORDER BY [DossierNumber] DESC
SET @sql = 'ALTER SEQUENCE [BSF_SEQ_DOSSIER_NUMBER] RESTART WITH ' + @sequenceNumber
PRINT @sequenceNumber
PRINT @sql
EXEC(@sql)
GO
After we run this query (because the sequence got reset during the previous deployment), this will mark the sequence to be reset during the next deployment (which forces us to run this query again, ending in an infinite loop).
With following query, the problem disappears. We only need to run this query once, after which the sequence will no longer be reset during any of the following deployments.
DECLARE @sequenceNumberTarget AS INT;
DECLARE @sequenceNumberCurrentValue AS INT;
SELECT TOP 1 @sequenceNumberTarget = CONVERT(VARCHAR, CAST(SUBSTRING([dossier].[DossierNumber], 6, 4) AS INT)) FROM [Dossier] [dossier] WHERE [dossier].[DossierNumber] LIKE CONCAT(YEAR(GETDATE()), '%') ORDER BY [DossierNumber] DESC;
SELECT @sequenceNumberCurrentValue = CAST(current_value AS INT) FROM sys.sequences WHERE name = 'BSF_SEQ_DOSSIER_NUMBER';
PRINT CONCAT('Sequence number target: ', @sequenceNumberTarget);
PRINT CONCAT('Sequence number current value: ', @sequenceNumberCurrentValue);
WHILE (@sequenceNumberCurrentValue < @sequenceNumberTarget)
BEGIN
SET @sequenceNumberCurrentValue = NEXT VALUE FOR [BSF_SEQ_DOSSIER_NUMBER];
END