283

I have SQL Server database and I want to change the identity column because it started with a big number 10010 and it's related with another table, now I have 200 records and I want to fix this issue before the records increases.

What's the best way to change or reset this column?

Darren
  • 68,902
  • 24
  • 138
  • 144
Abdulsalam Elsharif
  • 4,773
  • 7
  • 32
  • 66

20 Answers20

374

You can not update identity column.

SQL Server does not allow to update the identity column unlike what you can do with other columns with an update statement.

Although there are some alternatives to achieve a similar kind of requirement.

  • When Identity column value needs to be updated for new records

Use DBCC CHECKIDENT which checks the current identity value for the table and if it's needed, changes the identity value.

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
  • When Identity column value needs to be updated for existing records

Use IDENTITY_INSERT which allows explicit values to be inserted into the identity column of a table.

SET IDENTITY_INSERT YourTable {ON|OFF}

Example:

-- Set Identity insert on so that value can be inserted into this column
SET IDENTITY_INSERT YourTable ON
GO
-- Insert the record which you want to update with new value in the identity column
INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
GO
-- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
DELETE FROM YourTable WHERE ID=3
GO
--Now set the idenetity_insert OFF to back to the previous track
SET IDENTITY_INSERT YourTable OFF
Community
  • 1
  • 1
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • 7
    DBCC Reset the next new record, but what i want now to change the existing records. – Abdulsalam Elsharif Oct 03 '13 at 09:43
  • can you give example please ? – Abdulsalam Elsharif Oct 03 '13 at 09:49
  • 54
    @sachin this is not updating an existing IDENTITY this is manually inserting – Phill Greggan Jan 26 '15 at 08:08
  • 3
    @PhillGreggan yes, this is the best possible solution to achieve this. You can't update the Identity column as you update the normal ones. – Sachin Jan 26 '15 at 08:44
  • 44
    This accepted answer does not answer the question, which is how to **update** an identity column (e.g. `UPDATE YourTable SET IdentityCol = 13`). `SET IDENTITY_INSERT YourTable ON` only allows INSERTs, not UPDATEs. – Ian Boyd Dec 28 '17 at 21:52
  • 3
    I don't think it is useful to answer a "How to ..." question with "You cannot ..." or, at least, don't vote it as best answer as it doesn't resolve the problem. The reply from @Luv does resolve the problem even though it is not an easy operation or not recommended by design. – Lucky Brain Jul 12 '20 at 12:24
  • It does answer the question, which is that it is not possible to use an update, and then goes on to show how it can be done. read much? – TugboatCaptain Nov 10 '21 at 06:16
  • Remember: All fields must be declared in Insert into (and select) – R.Alonso Nov 10 '22 at 09:01
94

If got your question right you want to do something like

update table
set identity_column_name = some value

Let me tell you, it is not an easy process and it is not advisable to use it, as there may be some foreign key associated on it.

But here are steps to do it, Please take a back-up of table

Step 1- Select design view of the table

enter image description here

Step 2- Turn off the identity column

enter image description here

Now you can use the update query.

Now redo the step 1 and step 2 and Turn on the identity column

Reference

Prahalad Gaggar
  • 11,389
  • 16
  • 53
  • 71
  • 1
    I have another table related with this table, I thing i can't do that – Abdulsalam Elsharif Oct 03 '13 at 10:04
  • 5
    Hence the statement ***it is not advisable*** `:)` – Prahalad Gaggar Oct 03 '13 at 10:07
  • 5
    @AbdusalamElsherif But you asked how to change the identity column. – paparazzo Oct 03 '13 at 13:28
  • @luv at least you have answered to the question that was asked – Phill Greggan Jan 26 '15 at 08:09
  • I use this procedure for setting the id in my development database. It would be nice if there was a command that let me do it anyway, but this works. – Jeff Davis Apr 25 '16 at 19:24
  • This might work. It did not for me, I'm guessing because other tables have Foreign Keys to the column in the table I want to take identity insert off from. Grrrr – clamum Jun 27 '17 at 20:10
  • I found this bit of SQL to do the same thing, haven't tried it yet:*********************** sp_configure 'allow update', 1 go reconfigure with override go update syscolumns set colstat = 0 --turn off bit 1 which indicates identity column where id = object_id('table_name') and name = 'column_name' go exec sp_configure 'allow update', 0 go reconfigure with override go *********************** – Ken Forslund Oct 23 '19 at 19:50
  • Good reply, however I would advise the following: When the database designer decided to make the column as IDENTITY he had many reasons to design it that way so it is usually not recommended to update an IDENTITY column as there could exist indirect foreign keys in other databases or existing reports, hard-coded web links, etc. which would get broken referencing the original identifier; this applies to any identifier, not only IDENTITY. So I would recommend to do this operation with caution and make sure no reports, web-links, etc. have been published containing the original identifiers. – Lucky Brain Jul 12 '20 at 12:39
  • It appears that if you already have data in the table it gives an error saying " Table needs to be dropped and recreated" – user2040021 Dec 31 '20 at 23:30
77

You need to

set identity_insert YourTable ON

Then delete your row and reinsert it with different identity.

Once you have done the insert don't forget to turn identity_insert off

set identity_insert YourTable OFF
R S P
  • 997
  • 5
  • 8
  • This is so much easier and safer than turning off Identity for the column! – Protector one Apr 14 '17 at 10:32
  • This is safer, and easy for a small number of records, but doesn't properly answer the question. Turning off identity, though more dangerous and sometimes impossible, does allow you to update the identity column. – Matthew Hudson Sep 05 '18 at 13:50
33
--before running this make sure Foreign key constraints have been removed that reference the ID. 

--set table to allow identity to be inserted
SET IDENTITY_INSERT yourTable ON;
GO
--insert everything into a temp table
SELECT * 
INTO #tmpYourTable
FROM yourTable

--clear your table
DELETE FROM yourTable
--insert back all the values with the updated ID column
INSERT INTO yourTable (IDCol, OtherCols)
SELECT ID+1 as updatedID --put any other update logic to the ID here
, OtherCols FROM #tmpYourTable
--drop the temp table
DROP TABLE #tmpYourTable
--put identity back to normal
SET IDENTITY_INSERT yourTable OFF;
GO
kuklei
  • 1,115
  • 11
  • 14
  • 1
    Just a performance tip if the table is very large, instead of doing a delete on table do a Truncate Table yourTable. It is instantaneous. Caution though, no turning back with truncate as it is not logged. – kuklei Oct 27 '17 at 08:11
  • 2
    @kuklei- truncate is logged. It's a common misconception. Truncate operates at the page level and logs a list of the pages it removes. This is why it is so fast. DELETE is row based and is required if FK's are involved, truncate won't deal with them and presents an error. Of course, either case you need to be using Full Recovery model (not Simple) and have a log backup. It is possible to restore to before the truncate operation. Regardless of model, you can also try it out... BEGIN TRAN TRUNCATE table MyTable ROLLBACK. Your data will still be there. – ripvlan Feb 01 '22 at 17:03
13

Try using DBCC CHECKIDENT:

DBCC CHECKIDENT ('YourTable', RESEED, 1);
Darren
  • 68,902
  • 24
  • 138
  • 144
  • 1
    That doesn't allow updating the identity column. That statement merely resets the identity value that will be used when new records are inserted and does not change any records. – Suncat2000 Jun 06 '22 at 13:44
7
SET IDENTITY_INSERT dbo.TableName ON
INSERT INTO dbo.TableName 
(
    TableId, ColumnName1, ColumnName2, ColumnName3
)
VALUES
(
    TableId_Value, ColumnName1_Value, ColumnName2_Value, ColumnName3_Value
)

SET IDENTITY_INSERT dbo.TableName OFF

When using Identity_Insert don't forget to include the column names because sql will not allow you to insert without specifying them

befree2j
  • 361
  • 5
  • 11
4
DBCC CHECKIDENT(table_name, RESEED, value)

table_name = give the table you want to reset value

value=initial value to be zero,to start identity column with 1

Igor Borisenko
  • 3,806
  • 3
  • 34
  • 49
Yasmeen Ansari
  • 319
  • 2
  • 4
  • 15
4

copy your table to a new table without identity column.

    select columns into newtable from yourtable

add an identity column to newtable with new seed and make it as a primary key

    ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY
user4002899
  • 49
  • 1
  • 1
3

You can also use SET IDENTITY INSERT to allow you to insert values into an identity column.

Example:

SET IDENTITY_INSERT dbo.Tool ON
GO

And then you can insert into an identity column the values you need.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
3

There's a few ways to do this as I've seen., but the best and faster way in my opinion is the following one:

The identity columns have a counter that isn't necessarily the same as the columns registered, you can see the value of this counter with the folowing SQL command:

DBCC CHECKIDENT('tableName', NORESEED);

Then, if you want to edit the identity column you will not be able, but I recommend to make a new register after reseeding the counter to the number you need. To reseed the counter use this command:

DBCC CHECKIDENT('tableName', RESEED, desiredNumber);
2

I had similar problem I needed update some IDs what I did was ( i needed to Increase them by 10k ):

set identity_insert YourTable ON

INSERT INTO YourTable 
   ([ID]
   ,[something1]
   ,[something2]
   ,[something3])
SELECT 
   ([ID] + 10000)
   ,[something1]
   ,[something2]
   ,[something3]) 
FROM YourTable
WHERE something1 = 'needs updeted id' 
   AND something2 = 'some other condition'

set identity_insert YourTable OFF

DELETE FROM YourTable 
WHERE ID >= 'your old ID From' 
   AND ID <= 'Your old ID To' 

And that's it. Hope you understand this logic, in my case there was also PK-FK keys connection with other tables, which meant i had to update them, before i could delete from 'YourTable' original rows.

I know there is already answers to this I just wanted to leave SQL query as example,

Dharman
  • 30,962
  • 25
  • 85
  • 135
Emilis Vadopalas
  • 1,019
  • 2
  • 14
  • 22
1

Complete solution for C# programmers using command builder

First of all, you have to know this facts:

  • In any case, you cannot modify an identity column, so you have to delete the row and re-add with new identity.
  • You cannot remove the identity property from the column (you would have to remove to column)
  • The custom command builder from .net always skips the identity column, so you cannot use it for this purpose.

So, once knowing that, what you have to do is. Either program your own SQL Insert statement, or program you own insert command builder. Or use this one that I'be programmed for you. Given a DataTable, generates the SQL Insert script:

public static string BuildInsertSQLText ( DataTable table )
{
    StringBuilder sql = new StringBuilder(1000,5000000);
    StringBuilder values = new StringBuilder ( "VALUES (" );
    bool bFirst = true;
    bool bIdentity = false;
    string identityType = null;

    foreach(DataRow myRow in table.Rows) 
    {
        sql.Append( "\r\nINSERT INTO " + table.TableName + " (" );

        foreach ( DataColumn column in table.Columns )
        {
            if ( column.AutoIncrement )
            {
                bIdentity = true;

                switch ( column.DataType.Name )
                {
                    case "Int16":
                        identityType = "smallint";
                        break;
                    case "SByte":
                        identityType = "tinyint";
                        break;
                    case "Int64":
                        identityType = "bigint";
                        break;
                    case "Decimal":
                        identityType = "decimal";
                        break;
                    default:
                        identityType = "int";
                        break;
                }
            }
            else
            {
                if ( bFirst )
                    bFirst = false;
                else
                {
                    sql.Append ( ", " );
                    values.Append ( ", " );
                }
                sql.Append ("[");
                sql.Append ( column.ColumnName );
                sql.Append ("]");

                //values.Append (myRow[column.ColumnName].ToString() );

                if (myRow[column.ColumnName].ToString() == "True")
                    values.Append("1");
                else if (myRow[column.ColumnName].ToString() == "False")
                    values.Append("0");
                else if(myRow[column.ColumnName] == System.DBNull.Value)    
                    values.Append ("NULL");
                else if(column.DataType.ToString().Equals("System.String"))
                {
                    values.Append("'"+myRow[column.ColumnName].ToString()+"'");
                }
                else
                    values.Append (myRow[column.ColumnName].ToString());
                    //values.Append (column.DataType.ToString() );
            }
        }
        sql.Append ( ") " );
        sql.Append ( values.ToString () );
        sql.Append ( ")" );

        if ( bIdentity )
        {
            sql.Append ( "; SELECT CAST(scope_identity() AS " );
            sql.Append ( identityType );
            sql.Append ( ")" );
        }
        bFirst = true;
        sql.Append(";");
        values = new StringBuilder ( "VALUES (" );
    } //fin foreach
    return sql.ToString ();
}
Dale K
  • 25,246
  • 15
  • 42
  • 71
1
ALTER TABLE tablename add newcolumn int
update tablename set newcolumn=existingcolumnname
ALTER TABLE tablename DROP COLUMN existingcolumnname;
EXEC sp_RENAME 'tablename.oldcolumn' , 'newcolumnname', 'COLUMN'
update tablename set newcolumnname=value where condition

However above code works only if there is no primary-foreign key relation

Jekin Kalariya
  • 3,475
  • 2
  • 20
  • 32
1

Update is not allowed: but you can

  • INSERT new data with correct key
  • Delete reg

import: all fields must be declared in insert into sample: reg 5 must be changed to 4:

    set IDENTITY_INSERT Gastos_ReclamacionCausa on
insert into Gastos_ReclamacionCausa
    (IDCausa,TextoCombo,Asunto,Mensaje,EsBaja)
select 4,TextoCombo,Asunto,Mensaje,EsBaja from Gastos_ReclamacionCausa where idcausa=5
delete from  Gastos_ReclamacionCausa where idcausa = 5
set IDENTITY_INSERT Gastos_ReclamacionCausa off
R.Alonso
  • 989
  • 1
  • 8
  • 9
0

I have solved this problem firstly using DBCC and then using insert. For example if your table is

Firstly set new current ID Value on the table as NEW_RESEED_VALUE

MyTable { IDCol, colA, colB }

    DBCC CHECKIDENT('MyTable', RESEED, NEW_RESEED_VALUE)

then you can use

    insert into MyTable (colA, ColB) select colA, colB from MyTable

This would duplicate all your records but using new IDCol value starting as NEW_RESEED_VALUE. You can then remove higher ID Value duplicate rows once your have removed/moved their foreign key references, if any.

Softec
  • 1,087
  • 11
  • 14
  • 1
    This is a decent idea, but the New_reseed_value is the current seed, and the next number which will be used will be 1 more than that value. So if you want the next inserted row to be identity 10, then NEW_RESEED_VALUE must be set to 9. – LarryBud Feb 17 '17 at 02:40
0

You can create a new table using the following code.

SELECT IDENTITY (int, 1, 1) AS id, column1, column2
INTO dbo.NewTable
FROM dbo.OldTable

Then delete the old db, and rename the new db to the old db's name. Note: that column1 and column2 represent all the columns in your old table that you want to keep in your new table.

Sean H. Worthington
  • 1,701
  • 15
  • 9
0

I did the following:

  1. MOVE related data into temporary storage
  2. UPDATE primary key/identity column value (dropping and creating constraints)
  3. RE-INSERT related data with new foreign key value

I wrapped my solution in a STORED PROCEDURE:

CREATE PROCEDURE [dbo].[UpdateCustomerLocationId]
    @oldCustomerLocationId INT,
    @newCustomerLocationId INT
AS
  /* 
    Updates CustomerLocation.CustomerLocationId @oldCustomerLocationId to @newCustomerLocationId
    
    Example:
        EXEC [dbo].[UpdateCustomerLocationId] 
            @oldCustomerLocationId = 6154874, 
            @newCustomerLocationId = 50334;
    */

BEGIN

    SET NOCOUNT ON;
    
    -- exit if @oldCustomerLocationId does not exists
    IF NOT EXISTS (SELECT * FROM dbo.CustomerLocation cl WHERE cl.CustomerLocationId = @oldCustomerLocationId)
    BEGIN
        PRINT CONCAT('CustomerLocationId ''', @oldCustomerLocationId, ''' (@oldCustomerLocationId) does not exist in dbo.CustomerLocation');
        RETURN 1; -- 0 = success, > 0 = failure
    END

    -- exit if @newCustomerLocationId already exists
    IF EXISTS (SELECT * FROM dbo.CustomerLocation cl WHERE cl.CustomerLocationId = @newCustomerLocationId)
    BEGIN
        PRINT CONCAT('CustomerLocationId ''', @newCustomerLocationId, ''' (@newCustomerLocationId) already exists in dbo.CustomerLocation');
        RETURN 2; -- 0 = success, > 0 = failure
    END
    

    BEGIN TRAN;


        BEGIN -- MOVE related data into temporary storage

            IF EXISTS (SELECT * FROM dbo.CustomerLocationData t WHERE t.CustomerLocationId = @oldCustomerLocationId) BEGIN
    
                IF OBJECT_ID('tempdb..#CustomerLocationData') IS NOT NULL
                    DROP TABLE #CustomerLocationData;

                SELECT * INTO #CustomerLocationData FROM dbo.CustomerLocationData t WHERE t.CustomerLocationId = @oldCustomerLocationId;
                DELETE t FROM dbo.CustomerLocationData t WHERE t.CustomerLocationId = @oldCustomerLocationId;

            END

        END


        BEGIN -- UPDATE dbo.CustomerLocation

            -- DROP CONSTRAINTs
            ALTER TABLE [dbo].[CustomerLocation] DROP CONSTRAINT [UC_CustomerLocation];

            -- INSERT OLD record with new CustomerLocationId
            SET IDENTITY_INSERT dbo.CustomerLocation ON;

            INSERT INTO dbo.CustomerLocation
            (
                CustomerLocationId, CustomerId, LocationId, CustomerLocationIdent, CustomerLocationIdent2, LocationIdent, LocationName, CustomerDistrictId, 
                CustomerLocationGUID, UpdatedOn, IssueManager, EnrollSelfMonitoring, TemperatureControlDeadlineHour, CreatedOn, OperationBegin, ActiveCustomer, 
                Comments, LocationName2, ParentGroup, TempString1, TempString2, TempString3, TempString4, TempString5, AutoInheritFromLocation, ClassificationPrimary
            )
            SELECT @newCustomerLocationId AS CustomerLocationId, CustomerId,LocationId, CustomerLocationIdent, CustomerLocationIdent2, LocationIdent, LocationName, CustomerDistrictId,
                CustomerLocationGUID, UpdatedOn, IssueManager, EnrollSelfMonitoring, TemperatureControlDeadlineHour, CreatedOn, OperationBegin, ActiveCustomer,
                Comments,LocationName2, ParentGroup, TempString1, TempString2, TempString3, TempString4, TempString5, AutoInheritFromLocation, ClassificationPrimary
            FROM dbo.CustomerLocation 
            WHERE CustomerLocationId = @oldCustomerLocationId;

            SET IDENTITY_INSERT dbo.CustomerLocation OFF;

            -- DELETE OLD record
            DELETE cl FROM dbo.CustomerLocation cl WHERE cl.CustomerLocationId = @oldCustomerLocationId;

            -- ADD CONSTRAINTS
            ALTER TABLE [dbo].[CustomerLocation] ADD CONSTRAINT [UC_CustomerLocation] UNIQUE NONCLUSTERED ([CustomerId], [LocationId]);

        END


        BEGIN -- re-INSERT related data from temporary storage

            IF OBJECT_ID('tempdb..#CustomerLocationData') IS NOT NULL BEGIN
                SET IDENTITY_INSERT dbo.CustomerLocationData ON;
                INSERT INTO dbo.CustomerLocationData (Guid, CustomerLocationId, CustomerLocationDataTypeId, Date, Category, Data)
                SELECT Guid, @newCustomerLocationId CustomerLocationId, CustomerLocationDataTypeId, Date, Category, Data FROM #CustomerLocationData;
                SET IDENTITY_INSERT dbo.CustomerLocationData OFF;
            END

        END


    COMMIT TRAN;

END
mortenma71
  • 1,078
  • 2
  • 9
  • 27
0

This happened to me because I did a merge that was updating the ID that I was doing the Merge on.

Example that did not work (note ClownID):

    MERGE ArchitectMain.dbo.BackendClowns AS TGT 
   USING (
    SELECT ClownID
        ,ClownName
        ,Description
        ,Active
        ,EmailSubject
        ,AddedBy
        ,Added
    FROM #temptable1
    ) AS SRC(ClownID, ClownName, Description, Active, EmailSubject, AddedBy, Added)
    ON (TGT.ClownID = SRC.ClownID)
WHEN MATCHED
    THEN
        UPDATE
        SET ClownID = SRC.ClownID
            ,ClownName = SRC.ClownName
            ,Description = SRC.Description
            ,Active = SRC.Active
            ,EmailSubject = SRC.EmailSubject
            ,AddedBy = SRC.AddedBy
            ,Added = SRC.Added;

Example that worked (note ClownID):

MERGE ArchitectMain.dbo.BackendClowns AS TGT
USING (
    SELECT ClownID
        ,ClownName
        ,Description
        ,Active
        ,EmailSubject
        ,AddedBy
        ,Added
    FROM #temptable1
    ) AS SRC(ClownID, ClownName, Description, Active, EmailSubject, AddedBy, Added)
    ON (TGT.ClownID = SRC.ClownID)
WHEN MATCHED
    THEN
        UPDATE
        SET ClownName = SRC.ClownName
            ,Description = SRC.Description
            ,Active = SRC.Active
            ,EmailSubject = SRC.EmailSubject
            ,AddedBy = SRC.AddedBy
            ,Added = SRC.Added;
            
user3407335
  • 106
  • 1
  • 6
0

This solution relies on the ALTER TABLE SWITCH statement. The documentation is very focused on partitions but it can be applied here - with no partitions involved. It provides a very fast means of moving data from one table to another. There is a long list of restrictions but one notable exception to that list is the following.

The IDENTITY property is not considered.

I.e. You can use the ALTER TABLE SWITCH statement to move data from one table to another even if the target does not have identity defined the same way that the source does.

Note that in my scenario, the identity column was not referenced by any foreign keys. This solution could still be used if that is not the case but you would additionally need to update the foreign key values in the referencing tables.

  1. Adjust the script for the table in question by doing the following.
    1. Choose a new (temporary) name.
    2. Give all of the table constraints unique names.
    3. Remove the identity definition.

enter image description here

  1. Run the following statement to move the data from the existing table to the new, temporary one that you created above.
ALTER TABLE <EXISTING> SWITCH TO <NEW>;
  1. Run the following statement after inserting the name of the table and adjusting the columns names if necessary. This will squash the IDs down to start at 1 with no gaps. This will probably be the step that takes longest to complete.
WITH ids as
(
    SELECT
        ID,
        ROW_NUMBER() OVER (ORDER BY ID) [NewID]
    FROM
        <NEW>
)
UPDATE
    ids
SET
    ID = ids.[NewID];
  1. Run the following statement to swap the data back from the temporary table into the existing one.
ALTER TABLE SWITCH <NEW> TO <EXISTING>;
  1. Reseed the identity column so that new identity values will follow on from the highest in the table.
DBCC CHECKIDENT ('dbo.FeeItem', RESEED, 0); --Set it to a value that is too low.
DBCC CHECKIDENT ('dbo.FeeItem', RESEED); --Will automatically update it to the maximum value that currently exists in the table.
DBCC CHECKIDENT ('dbo.FeeItem', NORESEED); --Will describe how the identity ends up so that we can check it.
  1. Now just drop the new, temporary table.
Scott Munro
  • 13,369
  • 3
  • 74
  • 80
-1

If you specifically need to change the primary key value to a different number (ex 123 -> 1123). The identity property blocks changing a PK value. Set Identity_insert isn't going to work. Doing an Insert/Delete is not advisable if you have cascading deletes (unless you turn off referential integrity checking).

EDIT: Newer versions of SQL don't allow changing the syscolumns entity, so part of my solution has to be done the hard way. Refer to this SO on how to remove Identity from a primary key instead: Remove Identity from a column in a table This script will turn off identity on a PK:

***********************

sp_configure 'allow update', 1
go
reconfigure with override
go


update syscolumns set colstat = 0 --turn off bit 1 which indicates identity column
where id = object_id('table_name') and name = 'column_name'
go


exec sp_configure 'allow update', 0
go
reconfigure with override
go

***********************

Next, you can set the relationships so they'll update the foreign key references. Or else you need to turn off relationship enforcement. This SO link shows how: How can foreign key constraints be temporarily disabled using T-SQL?

Now, you can do your updates. I wrote a short script to write all my update SQL based on the same column name (in my case, I needed to increase the CaseID by 1,000,000:

select 
'update ['+c.table_name+'] SET ['+Column_Name+']=['+Column_Name+']+1000000'
from Information_Schema.Columns as c
JOIN Information_Schema.Tables as t ON t.table_Name=c.table_name and t.Table_Schema=c.table_schema and t.table_type='BASE TABLE'
where Column_Name like 'CaseID' order by Ordinal_position

Lastly, re-enable referential integrity and then re-enable the Identity column on the primary key.

Note: I see some folks on these questions ask WHY. In my case, I have to merge data from a second production instance into a master DB so I can shut down the second instance. I just need all the PK/FKs of operations data to not collide. Meta-data FKs are identical.

Ken Forslund
  • 340
  • 2
  • 9
  • 1
    Won't work. https://stackoverflow.com/questions/34336115/ad-hoc-updates-to-system-catalogs-are-not-allowed-in-sql-server-2012 – David Browne - Microsoft Jan 02 '21 at 21:14
  • it worked when I did it, which is why I wrote it all down for SO – Ken Forslund Jan 04 '21 at 19:30
  • Directly updating syscolumns was never supported, and last worked on SQL Server 2000. syscolumns was replaced with a view in SQL Server 2005, and now you'll get an error: `Ad hoc updates to system catalogs are not allowed.` You can see the view text with `sp_helptext 'sys.syscolumns'` – David Browne - Microsoft Jan 04 '21 at 19:38
  • worked on SQL2005. Now version concerns are important, but lead with that info next time. to do what I propose on a newer version, one might need to clone the identity column and drop the original, do the value update and then promote the replacement column back to identity. – Ken Forslund Jan 04 '21 at 19:42
  • Just tested on SQL 2005 SP2 (9.00.3042.00) and it fails with `Ad hoc updates to system catalogs are not allowed.` – David Browne - Microsoft Jan 04 '21 at 20:42
  • And I updated the text to send folks to a different SO on how to remove identity. Chillax. – Ken Forslund Jan 04 '21 at 20:44