2016-11-12 21 views
1

我在csv文件中有一个表(ID为numeric)。MS SQL Server(2008版或更高版本) - 如何在我的ID列中创建自动增量

我手动将信息从文件上传到SQL Server数据表(创建我的ID列为numeric)。

但是,我想重新创建我的ID列作为自动数字标识列,用最新的条目继续编号。

例:表有ID 1,5,10,我要重新创建的自动增量(标识)的ID列(离开我的旧的ID)和下一行插入继续与ID 11

我假设不存在实现此目的的单一方法。但我想知道我应该遵循的步骤。

+0

只是仰望'IDENTITY INSERT',让您可以在一个标识列插入自己的价值观。 – MatBailie

回答

0

感谢马特帮助我原题原始表。 我想分享一个C#方法,我用来自动化所有必要的步骤:

- 免责声明:使用this是我的类与MS SQL Server连接,用于读取一个SELECT语句(并返回一个数据表),并执行SQL查询等希望有人能帮忙,找到这段代码(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; 
    } 
} 
2

下面是一个脚本,让你知道你可以做到这一点。

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 

基本步骤

  • 重命名原始表(如果你希望你的新表是相同的名字的时候,我要重命名首先由于自动生成的新的约束条件等的名字表)
  • 与列作为一个标识列
  • 打开IDENTITY_INSERT
  • 创建新表中选择从旧表中的所有记录到新的一个
  • 关闭IDENTITY_INSERT
  • 您不必但可以使用任何数字开始标识身份,否则SQL服务器将根据最大标识值自动执行此操作。
  • 删除您重命名
+1

作品完美无瑕!谢谢马特。我需要的操作是IDENTITY INSERT – MiBol

相关问题