DECLARE @Versao VARCHAR(4)

SET @Versao = CASE 
                 WHEN LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR), 2) = '15' THEN '2019'
                 WHEN LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR), 2) = '14' THEN '2017'
                 WHEN LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR), 2) = '13' THEN '2016'
                 WHEN LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR), 2) = '12' THEN '2014'
                 WHEN LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR), 2) = '11' THEN '2012'
                 WHEN LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR), 2) = '10' THEN '2008'
                 WHEN LEFT(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR), 2) = '09' THEN '2005'
                 ELSE '2000'
              END
			  
IF CONVERT(INT,@Versao) >= 2012
BEGIN

	IF NOT EXISTS (SELECT * FROM sys.sequences WHERE name = 'SequenceProtocoloICMS')
	BEGIN

		DECLARE @START_SEQUENCE BIGINT
		DECLARE @Query_Sequence VARCHAR(4000)

		SELECT @START_SEQUENCE = MAX(PROT_ICMS_ST) + 1000
		FROM EST_NF_ENT_ENTRADA_ICMS_ST_MOV

		IF @START_SEQUENCE IS NULL
			SET @START_SEQUENCE = 1

		SET @Query_Sequence = CONCAT('
		CREATE SEQUENCE SequenceProtocoloICMS
			AS BIGINT
			START WITH ', @START_SEQUENCE, '
			INCREMENT BY 1;')

		EXECUTE (@Query_Sequence);

		-- Usando a sequence para obter o próximo valor
		DECLARE @NovoID INT = NEXT VALUE FOR SequenceProtocoloICMS;
	END
END