1

I have a table in csv file (with an ID as numeric).

I manually uploaded the information from the file to a SQL Server data table (creating my ID column as numeric).

But, I want to recreate my ID column as autonumeric ID column that continue the number with the latest entry.

Example: the table have the ID 1, 5, 10. I want to recreate the auto-incremental (IDENTITY) ID column (leaving my old ID's) and next row insertion continue with ID 11.

I suppose that doesn't exists a single method to achieve this. But I want to know the steps that I should follow.

MiBol
  • 1,985
  • 10
  • 37
  • 64

2 Answers2

2

Here is a script to give you an idea of one way you can do it.

IF OBJECT_ID('DELETEME.dbo.Tbl') IS NOT NULL
    BEGIN
        DROP TABLE Tbl
    END

IF OBJECT_ID('DELETEME.dbo.stageTbl') IS NOT NULL
    BEGIN
        DROP TABLE stageTbl
    END

CREATE TABLE Tbl (
    ID INT
    ,A CHAR(1)
)

INSERT INTO Tbl VALUES (1,'A'),(2,'B'),(10,'C')

SELECT *
FROM
    Tbl

EXEC sp_rename 'DELETEME.dbo.Tbl', 'stageTbl', 'OBJECT'
--renames original table

--create script for the new table
CREATE TABLE Tbl (
    ID INT NOT NULL IDENTITY(1,1)
    ,A CHAR(1)
)


--have to set IDENTITY_INSERT on to insert the ID into an IDENTITY column
SET IDENTITY_INSERT Tbl ON

INSERT INTO Tbl (ID, A)
SELECT ID, A
FROM
    stageTbl

SET IDENTITY_INSERT Tbl OFF

DROP TABLE stageTbl
--drops original table

DBCC CHECKIDENT('Tbl', RESEED, 222)
--sets the number you want to with next if you set as 222 the next identity will be 223

INSERT INTO Tbl (A) VALUES ('D')

SELECT *
FROM
    Tbl

Basic Steps

  • Renames original Table (if you want your new table to be the same name as the old, I like to rename first due to auto generated names of constraints etc on the new table)
  • Create the New table with the Column as an Identity column
  • Turn on IDENTITY_INSERT
  • Select all records from the old table into the new one
  • Turn off IDENTITY_INSERT
  • You don't have to but you can RESSED the identity to start with whatever number you want otherwise SQL-server will automatically do this based on the greatest ID value.
  • Drop the original table that you renamed
Matt
  • 13,833
  • 2
  • 16
  • 28
0

Thanks to Matt to help me out with the original question. I want to share a C# method that I used to automate all the necessary steps:

-- Disclaimer: the use of this is my class that connects with MS SQL Server, used to read a SELECT sentence (And returns a DataTable) and Execute SQL Queries, etc. Hope someone could find this code helpfully (AS-IS) --

/// <summary> Recreate an ID with auto-incremental when the table has the ID without this option.
/// <para>Automatically will rename the original table to TABLENAME_TO_DELETE (The process will require copy and recreate the table, then the process will duplicate the information) </para></summary>
/// <param name="strTable">SQL table</param>
/// <param name="strId">ID column</param>
public string recreateIdentityColumn(string strTable, string strId)
{
    string strLog = "Table: {0} - ID: {1}".fwFormat(strTable, strId);

    string strNewTable = strTable + "_" + fw.rnd(1, 1000).ToString() + fw.rnd(5000, 10000);
    DataTable dtTable = this.fillDataTable("SELECT COLUMN_NAME, DATA_TYPE, NUMERIC_PRECISION, NUMERIC_SCALE " +
                                            "FROM Information_SCHEMA.COLUMNS " +
                                            "WHERE TABLE_NAME = '" + strTable + "'");

    if (!dtTable.fwHasData()) throw new Exception("The current table '" + strTable + "' doesn't exists");
    DataRow[] drIdInfo = dtTable.Select("COLUMN_NAME = '" + strId + "'");

    if (!drIdInfo.fwHasData()) throw new Exception("The ID column '" + strId + "' doesn't exists in the table '" + strTable + "'");

    string strIdType = "";
    string strColumns = "";

    strIdType = drIdInfo[0]["DATA_TYPE"].fwEmpty("");

    if (strIdType.fwContains("decimal"))
        strIdType += "({0}, {1})".fwFormat(drIdInfo[0]["NUMERIC_PRECISION"].ToString(), drIdInfo[0]["NUMERIC_SCALE"].ToString());

    strLog += "\r\nID DataType: " + strIdType;

    foreach (DataRow drInfo in dtTable.Rows)
        strColumns += ",[" + drInfo["COLUMN_NAME"].ToString() + "]";

    strId = "[" + strId.TrimStart('[').TrimEnd(']') + "]";
    strColumns = strColumns.TrimStart(',');
    strLog += "\r\nColumns: " + strColumns;

    try
    {
        // Rule 1: Clone the table (Only the structure)
        this.executeQuery("SELECT TOP 0 * INTO " + strNewTable + " FROM " + strTable);

        // Rule 2: Remove the ID from the clone table
        this.executeQuery("ALTER TABLE " + strNewTable + " DROP COLUMN " + strId);

        // Rule 3: Add the ID column with the identity property
        this.executeQuery("ALTER TABLE " + strNewTable + " ADD " + strId + " " + strIdType + " IDENTITY(1,1)");

        // Rule 4: Allow manual insertion of ID in the identity column
        this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " ON");

        // Rule 5: Copy the rows into the table
        int intTotalRows = this.rowCount(strTable);
        int intTotalNewRows = this.executeQuery("INSERT INTO " + strNewTable + "(" + strColumns + ") " +
                            "SELECT " + strColumns + " FROM " + strTable);

        strLog += "\r\nOriginal rows {0} - New rows {1}".fwFormat(intTotalRows.ToString(), intTotalNewRows.ToString());

        // Rule 6: Return the insertion of identity rows to a normal state
        this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " OFF");

        // Rule 7: Rename the table with NO IDENTITY as OLD and rename the table with INDENTITY ID as NEW/ACTUAL
        this.executeQuery("EXEC sp_rename '" + strTable + "', '" + strTable + "_TO_DELETE', 'OBJECT'");
        this.executeQuery("EXEC sp_rename '" + strNewTable + "', '" + strTable + "', 'OBJECT'");
        strLog += "\r\nProcess run without problems";
        return strLog;
    }
    catch (Exception ex)
    {
        strLog += "\r\nException occur";
        throw ex;
    }
}
MiBol
  • 1,985
  • 10
  • 37
  • 64