Use of SET Identity_insert

Source: Internet
Author: User

Use of SET Identity_insert
SET Identity_insert [Database. [owner.] ] {table} {on | OFF}
--powerful self-added bars can be inserted into the record.
--database is the name of the data library.
--owner is all the names of the tables.
--table a unique field's table name
Examples:
--Create Products table. Create a test table
CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar (40))
Go
--inserting values into the Products table. Insert test data into the table
INSERT into Products (product) VALUES (' screwdriver ')
INSERT into Products (product) VALUES (' Hammer ')
INSERT into Products (product) VALUES (' saw ')
INSERT into Products (product) VALUES (' shovel ')
Go
SELECT * FROM Products
--Create a gap in the identity values. To remove the data by leaving gaps
DELETE Products
WHERE Product = ' saw '
Go
SELECT *
From Products
--At this point the id=3 record does not exist and is deleted.
Go
--Attempt to insert a explicit ID value of 3;
--should return a warning. Inserting data will be wrong at this time. Be interrupted.
INSERT into the products (ID, product) VALUES (3, ' garden shovel ')
--Hint: Cannot insert explicit value for identity column in table ' products ' while IDENTITY_INSERT is set to OFF.
-When the IDENTITY_INSERT is set off, insert self-add data cannot be specified in the table products (that is, the specific self increment value).
Go
--SET identity_insert to ON.
SET Identity_insert Products on
Go

--Attempt to insert a explicit ID value of 3 will be successful
INSERT into the products (ID, product) VALUES (3, ' garden shovel ')
Go

SELECT *
From Products
Go
--Drop Products table.
SET Identity_insert Products off
DROP TABLE Products
Go

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.