2016-11-12 7 views
1

IDがnumericのcsvファイルにテーブルがあります。MS SQL Server(Ver 2008以上) - ID列に基づいて自動インクリメンタルを再作成する方法

ファイルからSQL Serverのデータテーブルに情報を手動でアップロードしました(自分のID列をnumericとして作成しました)。

しかし、自分のID列を自動ID列として再作成して、最新のエントリの番号を続ける必要があります。

例:表には、ID 11

Iを続行ID 1、5、私は(私の古いIDのを残して)自動増分(IDENTITY)ID列を再作成したい10.次の行の挿入を持っていますこれを達成するための単一の方法が存在しないとします。しかし私は私が従うべきステップを知りたい。

+0

あなたがID列にして独自の値を挿入することができるようにちょうど 'IDENTITY INSERT'を見上げます。 – MatBailie

答えて

0

おかげと改名元のテーブル。 は、私は必要なすべての手順を自動化するために使用されるC#の方法を共有したい:

- 免責事項:thisの使用はSELECT文を読むために使用されるMS SQL Serverと接続している私のクラス、である(そして返しますDataTable)となど、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 

基本手順

  • は新しい上の制約の名前などを生成し、あなたの新しいテーブルが古いと同じ名前にしたい場合は、私が原因autoに最初に名前を変更したい(元のテーブルの名前を変更します表)
  • は新しいもの
  • 01に古いテーブルからすべてのレコードを選択してID列IDENTITY_INSERT上
  • 電源を入れ
  • として列を含む新しいテーブルを作成します。
  • IDENTITY_INSERTをオフにする
  • あなたはあなたがそうでなければ必要な番号で開始するようにIDを設定することはできますが、SQL ServerはIDの最大値に基づいてこれを自動的に行います。
  • ドロップあなたは、元の質問で私を助けるためにマットへ
+1

作品は完璧! Mattに感謝します。私が必要とした操作は、IDENTITY INSERT – MiBol

関連する問題