[SQL Server] [basic] how to assign values to auto-increment columns during insert

Source: Internet
Author: User

-- Create a test environment
If object_id ('tb') is not null drop table TB
Go
Create Table TB
(
Id int identity,
Code varchar (10 ),
Name varchar (20 ),
Constraint pk_tb primary key (ID)
)
Go
-- Query
Insert TB select 'A', 'A'
Insert TB values ('bb ', 'bb ')
Select * from TB
Go
-- Result
/*
ID code name
-----------------------------------------
1 aa
2 bb

(2 rows affected)
*/
Set identity_insert TB on
Insert TB select 3, 'A', 'A'
Insert TB values (3, 'bb', 'bb ')
Go
-- Result
/*
Message 8101, level 16, state 1, 6th rows
Only when the column list is used and identity_insert is on can an explicit value be specified for the ID column in The 'tb' table.
Message 8101, level 16, state 1, 7th rows
Only when the column list is used and identity_insert is on can an explicit value be specified for the ID column in The 'tb' table.
*/
Set identity_insert TB on
Insert Tb (ID, code, name) Select 3, 'A', 'A'
Insert Tb (ID, code, name) values (4, 'bb ', 'bb ')
Select * from TB
-- Result
/*
ID code name
-----------------------------------------
1 aa
2 bb
3 aa
4 BB

(Four rows affected)
*/

Related Article

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.