How can I insert identity manually?

后端 未结 4 758
遥遥无期
遥遥无期 2020-12-28 13:03
CREATE TABLE masterTbl (
id INT IDENTITY(1,1) CONSTRAINT pk_id PRIMARY KEY,
name VARCHAR(100))

INSERT INTO masterTbl VALUES (\'ABC\', \'XYZ\',\'PQR\')
相关标签:
4条回答
  • 2020-12-28 13:43

    Yes you can set identity fields manually executing

    SET IDENTITY_INSERT masterTbl ON
    

    then insert your data

    INSERT INTO masterTbl (id, name) VALUES (1, 'MNO') 
    ......
    

    and remember to call

    SET IDENTITY_INSERT masterTbl OFF
    

    to reenable the correct functionality

    0 讨论(0)
  • 2020-12-28 13:48

    In it's simplest form, you need to temporarily allow the insertion of identity values

    SET IDENTITY_INSERT masterTbl ON
    INSERT INTO masterTbl (id, name) VALUES (1, 'MNO')
    SET IDENTITY_INSERT masterTbl OFF
    
    0 讨论(0)
  • 2020-12-28 13:48
    SET IDENTITY_INSERT masterTbl ON
    

    https://docs.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql?view=sql-server-2017

    0 讨论(0)
  • 2020-12-28 13:55

    It is possible performing the following steps:

    I. Enable identity insert, which will DISABLE SQL Server from automatically inserting values in the table's identity column:

    SET IDENTITY_INSERT ON
    

    II. Perform your "manual" insert operation, SPECIFYING all the affected column names:

    INSERT INTO masterTbl (id, name)
    VALUES (1, 'ABC',
            2, 'XYZ',
            4, 'PQR')
    
    • If you skip listing the column names, SQL Server will popup an error message.

    III. When you're done, reenable the auto identity value insertion by disabling the manual insert feature of earlier:

    SET IDENTITY_INSERT OFF
    

    IV. You're done!

    0 讨论(0)
提交回复
热议问题