¿Cómo actualizar la columna de identidad en SQL Server?


Tengo una base de datos SQL Server y quiero cambiar la columna de identidad porque se inició con un gran número 10010 y está relacionado con otra tabla, ahora tengo 200 registros y quiero solucionar este problema antes de que los registros aumenten.

¿Cuál es la mejor manera de cambiar o restablecer esta columna?

Author: a_horse_with_no_name, 2013-10-03

12 answers

SQL Server no permite actualizar el valor de la columna de identidad a diferencia de lo que se puede hacer con columnas normales. Por lo tanto, no es posible actualizar el valor de la columna de identidad.

Aunque hay algunas alternativas para cumplir con un tipo similar de requisito. Uno de ellos es:

USE DBCC CHECKIDENT

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)

Si desea actualizar el valor de la columna identidad de los registros existentes, debe establecer

set identity_insert YourTable ON

Ejemplo

-- 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 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 prevoius track
SET IDENTITY_INSERT YourTable OFF
 188
Author: Sachin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 08:14:45

Si tienes tu pregunta correcta, quieres hacer algo como

update table
set identity_column_name = some value

Déjame decirte, no es un proceso fácil y no es recomendable usarlo, ya que puede haber algunos foreign key asociados a ella.

Pero aquí están los pasos para hacerlo, Por favor tome un back-up de la tabla

Paso 1-Seleccionar vista de diseño de la tabla

introduzca la descripción de la imagen aquí

Paso 2-Desactivar la columna identidad

introduzca la descripción de la imagen aquí

Ahora puede usar la consulta update.

Ahora redo el paso 1 y el paso 2 y Encienda la columna identidad

Referencia

 43
Author: Luv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 10:00:13

Necesitas

set identity_insert YourTable ON

Luego borre su fila y vuelva a insertarla con una identidad diferente.

Una vez que haya hecho la inserción, no olvide desactivar identity_insert

set identity_insert YourTable OFF
 35
Author: R S P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 11:57:35
--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
 9
Author: kuklei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-02 11:47:01

Intente usar DBCC CHECKIDENT:

DBCC CHECKIDENT ('YourTable', RESEED, 1);
 4
Author: Darren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 09:41:38

Copie su tabla a una nueva tabla sin columna de identidad.

    select columns into newtable from yourtable

Añadir una columna de identidad a tablanueva con nuevas semillas y hacer como clave primaria

    ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY
 4
Author: user4002899,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-03 06:41:06

También puede utilizar SET IDENTITY INSERT para permitirle insertar valores en una columna de identidad.

Ejemplo:

SET IDENTITY_INSERT dbo.Tool ON
GO

Y luego puede insertar en una columna de identidad los valores que necesita.

 2
Author: DaveShaw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 09:43:09
DBCC CHECKIDENT(table_name, RESEED, value)

Table_name = dar la tabla que desea restablecer el valor

Valor = valor inicial para ser cero, para iniciar la columna de identidad con 1

 2
Author: Yasmeen Ansari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-04 07:50:33

(Solución completa para programadores de c# usando command builder)

En primer lugar, usted tiene que saber estos hechos: -En cualquier caso, no se puede modificar una columna de identidad, por lo que hay que eliminar la fila y volver a añadir con nueva identuty. -No puede eliminar la propiedad de identidad de la columna (tendría que eliminar a la columna) - El generador de comandos personalizado de. net siempre se salta la columna de identidad, por lo que no puede usarlo para este propósito.

Así que, una vez sabiendo eso, lo que tengo que hacerlo. Programe su propia instrucción SQL Insert o programe su propio generador de comandos insert. O usa este que estoy programado para ti. Dada una tabla de datos, genera el script SQL Insert:

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 (); ;
        }
 1
Author: Juan_Mallorca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-14 12:52:08

He resuelto este problema primero usando DBCC y luego usando insert. Por ejemplo, si su tabla es

Primero establezca el nuevo valor de ID actual en la tabla como NEW_RESEED_VALUE

MyTable { IDCol, colA, colB }

    DBCC CHECKIDENT('MyTable', RESEED, NEW_RESEED_VALUE)

Entonces puedes usar

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

Esto duplicaría todos sus registros pero usando el nuevo valor IDCol que comienza como NEW_RESEED_VALUE. A continuación, puede eliminar filas duplicadas de valor de ID más alto una vez que haya eliminado / movido sus referencias de clave externa, si cualquier.

 0
Author: Softec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-14 11:46:43

Puede crear una nueva tabla utilizando el siguiente código.

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

A continuación, elimine la base de datos antigua y cambie el nombre de la nueva base de datos por el nombre de la base de datos antigua. Nota: que column1 y column2 representan todas las columnas de la tabla antigua que desea mantener en la nueva tabla.

 0
Author: Sean H. Worthington,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-29 23:05:38
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

Sin embargo, el código anterior solo funciona si no existe una relación clave primaria-externa

 0
Author: Jekin Kalariya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-27 07:13:11