Update Auto Generated Primary Key Sql Server Set Identity_insert

Transact-SQL reference for the SET IDENTITYINSERT statement. When set to ON, this permits inserting explicit values into the identity column of a table. SET IDENTITYINSERT (Transact-SQL) - SQL Server Microsoft Docs.

  1. Update Auto Generated Primary Key Sql Server Set Identity_insertt
  2. Update Auto Generated Primary Key Sql Server Set Identity_insertt Off
  3. Update Auto Generated Primary Key Sql Server Set Identity_insert Sert Off
-->

Google cloud debian instance generate ssh key. APPLIES TO: SQL Server 2016 and later Azure SQL Database Azure Synapse Analytics (SQL DW) Parallel Data Warehouse

You can define a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. Creating a primary key automatically creates a corresponding unique clustered index, or a nonclustered index if specified as such.

Before You Begin

AUTO INCREMENT Field. Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted. Jun 26, 2013  IDENTITYINSERT, and Using Alphanumeric Autoincrement Primary Key – Learn more on the SQLServerCentral forums. SQL Server 2008. Create Primary Keys.; 2 minutes to read +6; In this article. APPLIES TO: SQL Server 2016 and later Azure SQL Database Azure Synapse Analytics (SQL DW) Parallel Data Warehouse You can define a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL.

Limitations and Restrictions

  • A table can contain only one PRIMARY KEY constraint.

  • All columns defined within a PRIMARY KEY constraint must be defined as NOT NULL. If nullability is not specified, all columns participating in a PRIMARY KEY constraint have their nullability set to NOT NULL.

Security

Permissions

Creating a new table with a primary key requires CREATE TABLE permission in the database and ALTER permission on the schema in which the table is being created.

Creating a primary key in an existing table requires ALTER permission on the table.

Using SQL Server Management Studio

To create a primary key

  1. In Object Explorer, right-click the table to which you want to add a unique constraint, and click Design.
  2. In Table Designer, click the row selector for the database column you want to define as the primary key. If you want to select multiple columns, hold down the CTRL key while you click the row selectors for the other columns.
  3. Right-click the row selector for the column and select Set Primary Key.

Caution

If you want to redefine the primary key, any relationships to the existing primary key must be deleted before the new primary key can be created. A message will warn you that existing relationships will be automatically deleted as part of this process.

A primary key column is identified by a primary key symbol in its row selector.

If a primary key consists of more than one column, duplicate values are allowed in one column, but each combination of values from all the columns in the primary key must be unique.

If you define a compound key, the order of columns in the primary key matches the order of columns as shown in the table. However, you can change the order of columns after the primary key is created. For more information, see Modify Primary Keys.

Using Transact-SQL

To create a primary key in an existing table

The following example creates a primary key on the column TransactionID in the AdventureWorks database.

To create a primary key in a new table

The following example creates a table and defines a primary key on the column TransactionID in the AdventureWorks database.

To create a primary key with clustered index in a new table

The following example creates a table and defines a primary key on the column CustomerID and a clustered index on TransactionID in the AdventureWorks database.

See Also

By: Ben Richardson Updated: 2018-09-26 Comments (6) Related: More >Identities

Problem

While designing a SQL Server database, the primary key column is often set to auto-increment. To do this, the IDENTITY constraint is set on the primary key column. The starting position and the increment step are passed as parameters to the IDENTITY column. Then whenever a new record is inserted, the value of the IDENTITY column is incremented by the pre-defined step, usually a number. Now if a record is deleted, the IDENTITY column value for that record is also deleted. If a new record is inserted, its value for the IDENTITY column will be incremented from the previous figure in the column. It is not possible to reuse the value that was originally used by the now deleted record. If you try to specify the value for the IDENTITY column, an error will be thrown. So how do you reuse the value that was assigned to the deleted record?

Solution

The solution to this problem is to switch on the SET IDENTITY INSERT flag, which is off by default. Switching the SET IDENTITY INSERT flag to ON allows for the insertion of any random value to the IDENTITY column, as long as it doesn't already exist.

In this article, I will explain (with the help of an example) how to insert a missing value into the IDENTITY column.

Setup Example Table and Data

First let’s create some dummy data. We will execute our sample queries on this new database.

In the script, we create a dummy database “School”. Next, we execute the script that creates a table named “Students”. If you look at the table design, you can see that it contains three columns Id, StudentName and StudentAge. The Id column is the primary key column with an IDENTITY constraint. Both the seed and step values for IDENTITY are set to 2. This means that the first record in the “Students” database will have the Id value of 2 and each subsequent record will have a value incremented by 2. Finally, we insert 5 random records into the Students table.

Now if you select all the records from the Students table, you will see that Id column will contain a sequence of values starting at 2 and incremented by 2 in each row. Execute the following script:

The output looks like this:

You can see that the first record has an id value of 2 while the 5th has a value of 10.

Generated

Now, suppose one of the students leaves the school and we want to delete his record. We can do so using a simple DELETE statement. Let’s delete the record of Jon:

Now if you again look at all the records in the Students table using SELECT statement, you will see the following output:

You can see from the output that record of the student “Jon” with Id 6 has been deleted.

Now let’s try to insert a record of a new student and see what Id it gets:

The above script inserts a record of a new student named “Jessica”, aged 27, to the Students table.

To see the Id assigned to the Jessica, again retrieve all records from the Students table using the SELECT statement as shown below:

The output looks like this:

You can see from the output that Jessica has been assigned the Id 12 instead of the Id 6 vacated by Jon. The reason for this behavior is the fact that by default IDENTITY column assigns a value to a new record by adding the step to previous maximum value in the column instead of filling the vacant values in the column. Since the previous maximum value in the Id column was 10, therefore Jessica is assigned 12, since the step is 2.

Depending upon the business rules of the application being developed, this behavior can be correct. For instance, a School may have a rule that even if a student leaves the school, his/her Id cannot be assigned to a new student. On the other hand, there can be a school that reassigns the Id of a student who leaves the school, to a new student.

Manually Insert Record with specific ID value

In the latter case, one of the solutions is to manually insert the Id value for the new student.

Let’s try to add a record of a new student and manually set the value for the Id column to 6 as shown below:

The above script inserts a record of a new student named “Nick”, aged 22, and Id 6, to the students table. When you try to execute the above script, an error will be thrown which looks likes this:

Msg 8101, Level 16, State 1, Line 26
An explicit value for the identity column in table 'Students' can only be specified when a column list is used and IDENTITY_INSERT is ON.

In simple words, the error says that since the flag IDENTITY_INSERT is off for the Id column, we cannot manually insert any values. Another important consideration is that we need to specify the column names as well while inserting data to IDENTITY column.

If we try to just specify the column names as mentioned in the above error message as follows:

We get this error message.

Msg 544, Level 16, State 1, Line 35
Cannot insert explicit value for identity column in table 'Students' when IDENTITY_INSERT is set to OFF.

To manually insert a new value into the Id column, we first must set the IDENTITY_INSERT flag ON as follows:

To set the IDENTIT_INSERT flag ON we need to use the SET statement followed by the flag name and the name of the table.

Now if we again try to insert the record of the student “Nick” with Id 6, no error will be thrown. Execute the following statement again:

You can see that we have specified the name of the columns as well for inserting a record.

Now again use SELECT statement to retrieve all records from students table in order to view if our new record has been inserted or not. The SELECT statement will return the following records.

Update Auto Generated Primary Key Sql Server Set Identity_insertt

You can see from the output that record of a new student named “Nick”, aged 22, and Id 6 has been inserted to the Students table.

Try Inserting Duplicate Values

If we try to insert duplicate values as follows:

We will get this error, since ID is the primary key for the table which has to be a unique value.

Msg 2627, Level 14, State 1, Line 35
Violation of PRIMARY KEY constraint 'PK__Students__3214EC071AD8EC3F'. Cannot insert duplicate key in object 'dbo.Students'. The duplicate key value is (6).
The statement has been terminated.

Note, that if the ID column was not a Primary Key we would be able to insert duplicate records.

Turn IDENTITY INSERT off

When you SET INDENTITY_INSERT ON it will stay on for the entire session (the time the query window is open). So once this is set you can insert as many records as you want. Also, this only applies for the session where this is turned on, so if you open another query window you would need to set this ON for that query window.

To turn off this option for the session, you would issue the following statement.

Next Steps
  • In this article, we saw that how we can use the SET IDENTITY_INSERT flag as ON in order to insert a record in the IDENTITY column which is not possible with default settings.
  • Check out these related articles:

Last Updated: 2018-09-26



About the author

Update Auto Generated Primary Key Sql Server Set Identity_insertt Off

Ben is the owner of Acuity Training, a UK based IT training business offering SQL training up to advanced administration courses.
View all my tips

Update Auto Generated Primary Key Sql Server Set Identity_insert Sert Off