Wednesday, April 12, 2023

Problem with deployments of automatically sequence by dacpac deployment using SqlPackage


Publish script is always includes restarting the sequence back to the 'start with' or 'minvalue' value.

How can I prevent to update sequence value by dacpac deployment using SqlPackage? .it means how to keep current value of sequence post dacpac deployment.

For example

```sql
CREATE SEQUENCE [dbo].[UUID_Sequence]
    AS NUMERIC (8)
    INCREMENT BY 1
    MINVALUE 10000
    CACHE 20;
```
and the publish script always includes the following:

```sql
ALTER SEQUENCE [dbo].[UUID_Sequence]
    RESTART WITH 10000;
GO
```
If exclude sequence object using publish profile but you have to manually deploy sequences so it will prevent to restart to initial value . it wont create sequence object if deploy in new environment so this solution wont solve problem completely.

```sh
::from Database publish profile file
	True

::from command line
	/p:ExcludeObjectType=Sequences
```
Solution: We can solve this issue by using below pre and post deployment scripts Pre-Deployment:
```sql
-- Capture next value of sequence UUID_Sequence for reseeding in post-deployment phase.
IF EXISTS (SELECT 1 FROM sys.sysobjects WHERE name = 'UUID_Sequence' AND [type] = 'SO')
BEGIN
	DECLARE @NextValue_UUID_Sequence decimal(28,0)
	SELECT @NextValue_UUID_Sequence = NEXT VALUE FOR dbo.UUID_Sequence;

	PRINT 'Sequence UUID_Sequence: current value is ' + CAST(@NextValue_UUID_Sequence AS VARCHAR(28))

	-- Store in a temp table for retrieval during reseed.
	SELECT @NextValue_UUID_Sequence AS NextValue INTO #Seed_UUID_Sequence
END
```
Post-Deployment:
```sql
/*
    This script reseeds dbo.UUID_Sequence to it's next value at the beginning of the deployment.
 */
IF OBJECT_ID('tempdb..#Seed_UUID_Sequence') IS NOT NULL
BEGIN
    DECLARE @fID VARCHAR(28)

	SET @fID = (SELECT NextValue FROM #Seed_UUID_Sequence)

    -- Prepare the statement to reseed the sequence
    DECLARE @sql NVARCHAR(MAX) = N'ALTER SEQUENCE dbo.UUID_Sequence RESTART WITH ' + @fID
    --PRINT @sql

    -- Execute
    EXEC sp_executesql @sql

    PRINT N'Sequence dbo.UUID_Sequence: seeded to '  + @fID
    drop table ##Seed_UUID_Sequence'
END
GO
```

No comments:

Post a Comment