Programming

SQL Server에서 ID 열을 업데이트하는 방법은 무엇입니까?

procodes 2020. 6. 4. 21:23
반응형

SQL Server에서 ID 열을 업데이트하는 방법은 무엇입니까?


SQL Server 데이터베이스가 있고 큰 숫자로 시작 10010하고 다른 테이블과 관련되어 있기 때문에 ID 열을 변경하고 싶습니다 . 이제 200 개의 레코드가 있으며 레코드가 증가하기 전에이 문제를 해결하려고합니다.

이 항목을 변경하거나 재설정하는 가장 좋은 방법은 무엇입니까?


SQL Server에서는 일반 열로 수행 할 수있는 것과 달리 ID 열의 값을 업데이트 할 수 없으므로 ID 열을 업데이트 할 수 없습니다 .

비슷한 종류의 요구 사항을 충족시키는 몇 가지 대안이 있지만. 그들 중 하나는 :

DBCC 인증 자 사용

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)

기존 레코드의 ID 열 값을 업데이트하려면 다음을 설정해야합니다.

set identity_insert YourTable ON

-- 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

질문이 바로 있다면 다음과 같은 일을하고 싶습니다.

update table
set identity_column_name = some value

쉬운 과정이 아니며 관련 과정이있을 수 있으므로 사용하지 않는 것이 좋습니다 foreign key.

그러나 여기 그것을 할 단계는, 테이크 바랍니다 back-up테이블을

1 단계-테이블의 디자인 뷰 선택

여기에 이미지 설명을 입력하십시오

2 단계-ID 열 끄기

여기에 이미지 설명을 입력하십시오

이제 update쿼리를 사용할 수 있습니다 .

이제 redo1 단계와 2 단계에서 ID 열을 켭니다.

참고


당신은 필요

set identity_insert YourTable ON

그런 다음 행을 삭제하고 다른 ID로 다시 삽입하십시오.

삽입을 완료하면 identity_insert를 끄는 것을 잊지 마십시오

set identity_insert YourTable OFF

--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

사용해보십시오 DBCC CHECKIDENT:

DBCC CHECKIDENT ('YourTable', RESEED, 1);

ID 열이없는 새 테이블에 테이블을 복사하십시오.

    select columns into newtable from yourtable

새로운 시드로 newtable에 ID 열을 추가하고 기본 키로 만듭니다.

    ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY

DBCC CHECKIDENT(table_name, RESEED, value)

table_name = 재설정하려는 테이블을 제공하십시오.

value = 초기 값은 0으로, ID 열을 1로 시작합니다.


You can also use SET IDENTITY INSERT to allow you to insert values into an identity column.

Example:

SET IDENTITY_INSERT dbo.Tool ON
GO

And then you can insert into an identity column the values you need.


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

However above code works only if there is no primary-foreign key relation


Complete solution for C# programmers using command builder

First of all, you have to know this facts:

  • In any case, you cannot modify an identity column, so you have to delete the row and re-add with new identity.
  • You cannot remove the identity property from the column (you would have to remove to column)
  • The custom command builder from .net always skips the identity column, so you cannot use it for this purpose.

So, once knowing that, what you have to do is. Either program your own SQL Insert statement, or program you own insert command builder. Or use this one that I'be programmed for you. Given a DataTable, generates the SQL Insert script:

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 ();
}

I have solved this problem firstly using DBCC and then using insert. For example if your table is

Firstly set new current ID Value on the table as NEW_RESEED_VALUE

MyTable { IDCol, colA, colB }

    DBCC CHECKIDENT('MyTable', RESEED, NEW_RESEED_VALUE)

then you can use

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

This would duplicate all your records but using new IDCol value starting as NEW_RESEED_VALUE. You can then remove higher ID Value duplicate rows once your have removed/moved their foreign key references, if any.


You can create a new table using the following code.

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

그런 다음 이전 db를 삭제하고 새 db의 이름을 이전 db의 이름으로 바꿉니다. 참고 : column1 및 column2는 새 테이블에 유지하려는 이전 테이블의 모든 열을 나타냅니다.


SET IDENTITY_INSERT dbo.TableName ON
INSERT INTO dbo.TableName 
(
    TableId, ColumnName1, ColumnName2, ColumnName3
)
VALUES
(
    TableId_Value, ColumnName1_Value, ColumnName2_Value, ColumnName3_Value
)

SET IDENTITY_INSERT dbo.TableName OFF

Identity_Insert를 사용할 때 sql은 열 이름을 지정하지 않고 삽입 할 수 없으므로 열 이름을 포함시키는 것을 잊지 마십시오.

참고 URL : https://stackoverflow.com/questions/19155775/how-to-update-identity-column-in-sql-server

반응형