Insert the self-growth (IDENTITY) column

 

SQL Server  数据库中,有一个表, 表里有一列(主键) ID, 建表时设置为自动增长,

 

 

 

当想插入数据时, 将ID 也插入, 需要将 表的 identity_insert 设置为 on

 

当完成插入时, 要将  表的 identity_insert 设置为 off

 

 

### SQL Server Identity Column Usage and Properties An identity column in SQL Server automatically generates numeric values when new rows are added to a table. This feature is particularly useful for generating unique identifiers without manual intervention[^1]. The `IDENTITY` property can be applied only to columns of the following data types: tinyint, smallint, int, bigint, decimal(p,0), or numeric(p,0). The syntax used during creation involves specifying two parameters: - **Seed**: Initial value assigned to an identity column. - **Increment**: Value that will be added to each subsequent row. For example, creating a table with an identity column looks like this: ```sql CREATE TABLE ExampleTable ( ID INT IDENTITY(1,1), Name NVARCHAR(50) ); ``` To insert into tables containing an identity column while allowing automatic generation of IDs, simply omit the identity column from the INSERT statement as shown below: ```sql INSERT INTO ExampleTable (Name) VALUES ('John Doe'); ``` If there's ever a need to explicitly specify a value for an identity column despite its setting, one could use the `SET IDENTITY_INSERT` command before performing inserts: ```sql SET IDENTITY_INSERT ExampleTable ON; INSERT INTO ExampleTable (ID, Name) VALUES (99,'Jane Smith'); SET IDENTITY_INSERT ExampleTable OFF; ``` Identity properties cannot directly modify existing non-identity columns; instead, dropping and recreating them might become necessary under such circumstances. However, altering other aspects related to identities—such as resetting seed values—is achievable through various methods including using system stored procedures provided by Microsoft SQL Server.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值