use PharmIndexTP DECLARE @TableName NVARCHAR(255); DECLARE @IdentityColumn NVARCHAR(255); declare @currentIdentityValue int; DECLARE @MaxIdentityValue INT; DECLARE @SQL NVARCHAR(MAX); declare @reseedSQL nvarchar(max)=''; -- Create a table variable to hold the list of tables DECLARE @Tables TABLE (TableName NVARCHAR(255)); -- Insert the tables into the table variable INSERT INTO @Tables (TableName) VALUES ('ServiceProvider'), ('ServiceProviderAddress'), ('ServiceProviderCommunication'), ('ServiceProviderCommunication2'), ('ServiceProviderECommunication'), ('ServiceProviderECommunication2'), ('ServiceProviderReference'), ('ServiceProviderRole') -- Cursor to iterate over the list of tables DECLARE TableCursor CURSOR FOR SELECT TableName FROM @Tables; OPEN TableCursor; FETCH NEXT FROM TableCursor INTO @TableName; WHILE @@FETCH_STATUS = 0 BEGIN -- Get the primary key column name which is assumed to be the identity column SELECT @IdentityColumn = [KU].[COLUMN_NAME] FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KU ON TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME WHERE TC.TABLE_NAME = @TableName AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY'; -- Get the maximum identity value for the current table SET @SQL = 'SELECT @MaxIdentityValue = MAX(' + @IdentityColumn + ') FROM ' + @TableName; EXEC sp_executesql @SQL, N'@MaxIdentityValue INT OUTPUT', @MaxIdentityValue OUTPUT; --print 'max value fetched' --fetch current identity value set @sql = 'SELECT @currentIdentityValue=IDENT_CURRENT('''+@tableName+''') '; exec sp_executesql @sql, N'@currentIdentityValue INT OUTPUT', @currentIdentityValue OUTPUT; --print 'identity value fetched' print 'table: "'+@tableName+'", column "'+@IdentityColumn+'" current column max value: '+cast(@MaxIdentityValue as varchar(50))+' identity value: '+cast(@currentIdentityValue as varchar(50)); -- Reseed the identity column if @currentIdentityValue < @MaxIdentityValue begin SET @SQL = 'DBCC CHECKIDENT (''' + @TableName + ''', RESEED, ' + CAST(ISNULL(@MaxIdentityValue, 0) AS NVARCHAR) + ')'; --EXEC sp_executesql @SQL; set @reseedSQL = @reseedSQL+char(13)+char(10)+@sql end FETCH NEXT FROM TableCursor INTO @TableName; END print @reseedSQL; CLOSE TableCursor; DEALLOCATE TableCursor;