REQUEST COMPLIMENTARY SQLS*PLUS LICENCE
IDENTITY INSERT table property in Microsoft SQL Server
IDENTITY SQL – The table property in Microsoft SQL Server is IDENTITY_INSERT. Using this property, we can insert an explicit value into the autoincrement column with IDENTITY that was previously deleted, i.e. fill in or recover missing ID values.
Probably, many SQL Server programmers had a situation when in the table in which the identifier specification is defined, for some reason, some records are removed, and then there is a need to restore these records, and with the values of the old identifiers.
The first thing that comes to mind is, of course, to remove the identification, insert the lines with the required values, and then restore the identification, but for this, as you understand, you need to perform a lot of manipulations that can affect the progress of the current work, so they must be done quickly, and better at a time when the database does not have any working users.
However, there is actually a simpler and most importantly correct way to insert values into a column of table identifiers. This is to use the IDENTITY INSERT property.
IDENTITY_INSERT property in Microsoft SQL Server
IDENTITY_INSERT is a table property that allows you to insert explicit values into the column of table identifiers, i.e. into the column with IDENTITY. The value of the inserted identifier can be either less than the current value or more, for example, to skip a certain interval of values.
When working with this property, it is necessary to take into account some nuances, let’s consider them:
- The IDENTITY_INSERT property can only take ON for one table in a session, i.e. IDENTITY_INSERT cannot be set to ON for two or more tables in a session simultaneously. If it is necessary to use IDENTITY_INSERT ON for several tables in one SQL instruction, you must first set the value to OFF for the table that has already been processed, and then set IDENTITY_INSERT to ON for the next table;
- If the IDENTITY value to be inserted is greater than the current value, the SQL server will automatically use the inserted value as the current value, i.e. if, for example, the next IDENTITY INSERT value is 5, and you use IDENTITY INSERT to insert an ID with a value of 6, then automatically the next ID value will be 7;
- In order to use IDENTITY_INSERT, a user must have the appropriate rights, i.e. to be the owner of the object or to be part of the sysadmin server role, the db_own or db_ddladm database role.
Example of using IDENTITY_INSERT in T-SQL
So, let’s look at a situation where we had to insert a value into a column of identifiers, let’s say a row with that value has been deleted and we need to restore it.
Let us start by looking at the source data.
Source data
For example, let’s create a test table with a column of IDENTITY identifiers and fill it with some data.
Note! The example uses the Microsoft SQL Server 2019 Express version.
CREATE TABLE Tab_1(
Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
TextData_1 VARCHAR(50) NOT NULL
);
GO
INSERT INTO Tab_1 (TextData_1)
VALUES ('Str_1'),
('Str_2'),
('Str_3'),
('Str_4'),
('Str_5');
GO
SELECT * FROM Tab_1;
Deletion of one record from the table
Now let’s delete the string where the identifier value is 3.
DELETE Tab_1
WHERE Id = 3;
SELECT * FROM Tab_1;
Recovering a deleted record with a certain identifier value
We do not have an entry with Id = 3 in our table and we need to restore it with Id = 3, for this purpose we, as beginners SQL programmers, try it this way first.
INSERT INTO Tab_1 (Id_1, TextData_1)
VALUES (3, 'Str_3');
As you can see, we failed to insert such a string, SQL Server returned the error “It is impossible to insert an explicit value for the column of identifiers in the table”.
To add a record with this value, let’s use the IDENTITY_INSERT property, i.e. set its value for the TestTable table to ON.
SET IDENTITY_INSERT Tab_1 ON;
INSERT INTO Tab_1 (Id_1, TextData_1)
VALUES (3, 'Str_3');
SELECT * FROM Tab_1;
This time everything was successful and the record with the recovered identifier value was added, as you can see.
Note! If the identifier column is the primary key, as in our example, then when you try to insert an identifier value that already exists, the PRIMARY KEY restriction will trigger, in other words, the unique keys continue to work.
IDENTITY
The IDENTITY attribute allows you to make a column identifier. This attribute can be assigned to columns of numerical types INT, SMALLINT, BIGINT, TYNIINT, DECIMAL and NUMERIC. When adding new data to a table, SQL Server will increment the value of this column in the last record by one. Typically, the identifier role is the same column that is the primary key, although in principle this is not necessary.
CREATE
TABLE
Customers
(
Id
INT
PRIMARY
KEY
IDENTITY,
Age
INT
,
FName NVARCHAR(20),
LName NVARCHAR(20),
Email
VARCHAR
(30),
Phone
VARCHAR
(20)
)
IDENTITY(seed_1, increment_1)
IDENTITY(1, 1)
Id
INT
IDENTITY (2, 3)
In this case, the countdown will start with 2, and the value of each subsequent record will increase by 3. That is, the first line will have the value of 2, the second – 5, the third – 8, etc.
Also note that in the table only one column should have this attribute.
SQL Tutorial – IDENTITY INSERT
MORE NEWS
PreambleNoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...
PreambleMongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...
5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...
The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...
PreambleMS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...
First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...
PreambleAtom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...
PreambleMongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...
FlexibilityOne of the most advertised features of MongoDB is its flexibility. Flexibility, however, is a double-edged sword. More flexibility means more...
PreambleSQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...
PreambleWriting an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...
PreambleOracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...
PreambleIBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...
What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....
PreambleIf you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...
PreambleStarting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...