	DECLARE @nextVal BIGINT       
      DECLARE @script AS NVARCHAR(255); 
	  DECLARE @sequenceName AS NVARCHAR(255); 
		SET @nextVal  = 5637144576
	DECLARE @ParmDefinition nvarchar(500);
	DECLARE @TableCount int;      
	
	DECLARE @currentValue BIGINT
	DECLARE @tabId INT
	DECLARE @tableId bigint
	DECLARE @startValFromSequence BIGINT;
	DECLARE @currentValFromSequence BIGINT;
	DECLARE @tableName AS NVARCHAR(255);
	  DECLARE @maxRecId BIGINT;
	  DECLARE @SQLQuery AS NVARCHAR(500)

		  SET @ParmDefinition = '@maxRecIdOut bigint output';
	  SET @TableCount = 0;

	  DECLARE sqldictcursor CURSOR FOR 
        SELECT dict.TABLEID, dict.SQLNAME
        FROM   SQLDICTIONARY dict            
        WHERE  dict.FIELDID = 0 and dict.FLAGS = 0

      OPEN sqldictcursor 

      FETCH next FROM sqldictcursor INTO @tableid, @tableName

      WHILE @@FETCH_STATUS = 0 
        BEGIN           
				  SET @sequenceName= 'SEQ_'+Cast(@tableId AS NVARCHAR);

				  IF EXISTS(select * from sys.sequences where name=@sequenceName)
				  BEGIN										
					  SET @TableCount = @TableCount +1;
					  --Print 'Processing ' + CAST(@TableCount as CHAR(10)) + '  ' + @TableName;

					  SELECT @startValFromSequence = CONVERT(BIGINT,start_value), @currentValFromSequence = CONVERT(BIGINT,current_value) from sys.sequences where name=@sequenceName
				  
					  SET @SQLQuery = 'SELECT @maxRecIdOut =  isnull(max(recid),0) from ' + @tableName;
							  
					  EXECUTE sp_executesql @SQLQuery, @ParmDefinition, @maxRecIdOut = @maxRecId output
					  -- There is an edge case when the current_value is equal to the start_value, which indicates that either start_value or start_value + 1
					  -- will be the next value returned by NEXT VALUE FOR [SEQ].
					  IF (@maxRecId > @currentValFromSequence or (@currentValFromSequence = @startValFromSequence and @maxRecId = @currentValFromSequence))
						BEGIN
							SET @nextVal  = @maxRecId+1
							SET @script = ' ALTER SEQUENCE ' + @sequenceName  + '  RESTART WITH ' + Cast ( @nextVal AS NVARCHAR) ; 				  
							EXEC (@script) ; 
						END
					END

				  FETCH next FROM sqldictcursor INTO @tableid, @tableName     
		END 

		close sqldictcursor
		Deallocate sqldictcursor



  	