简体   繁体   中英

Alter column identity with Microsoft.SqlServer.Smo

I've trying to change a column IDENTITY using Microsoft.SqlServer.Smo from a table with no dependencies and with all the data loaded previously (from another DB) but i get an error like this "Modifying the Identity property of the Column object is not allowed. You must drop and recreate the object with the desired property". The thing is that i tried to do this with Management Studio and it has no problem with it. Do you have any suggestions?. Thanks in Advance

This is the code:

foreach (Column source in sourcetable.Columns)
{
    try
    {
        if(source.Identity)
        {
            Column column = copiedtable.Columns[source.Name];

            // column.Computed = source.Computed;
            // column.ComputedText = source.ComputedText;

            column.Identity = source.Identity;
            column.IdentityIncrement = source.IdentityIncrement;
            column.IdentitySeed = source.IdentitySeed;

            column.Alter();
        }
    }
    catch { }
}

Try doing it in SSMS again and choose to script the action out instead of applying it directly. You'll find that it creates a temporary table with the identity property set to true (and everything else the same), copies your data from the live table into the temp table, drops the live table, and renames the temp table to be the live table. You'll need to do something similar with SMO.

Copying the table is easy enough: iterate over the columns, indexes, foreign keys, etc and create your new table that way (taking care to set the identity property correctly properly before you call Create() ). For moving the data, take a look at the Transfer class. Once that's done, it's a drop and rename (or a rename and rename if you want to be safe).

I'm a little surprised that SMO doesn't do this somehow under the covers (since SSMS uses SMO under the covers). If I find something else that makes it do this automatically, I'll let you know.

Are you trying to update an existing record, or add a new record? If you're adding a new record, then do an insert. If you're updating an existing record, don't overwrite the identity column value.

To insert identity values into a table in SQL Server you must tell the database to allow you to do this. Syntax is:

Set Identity_Insert [table] ON

When you're done you need to turn it off again.

Set Identity_Insert [table] OFF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM