2016-11-12 23 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

相關問題