当前位置: 移动技术网 > IT编程>数据库>MSSQL > sql自动增长标识导致导入数据问题的解决方法

sql自动增长标识导致导入数据问题的解决方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

沙迷之家,07073小游戏,深圳运输

对于一个设了自动增长标识的数据表来说,它的字段的值是由数据库自动设置的;这在导数据时很麻烦。

当我们导数据时,我们往往想想将标识字段的数据也导进来,怎么办呢?

方法有两种:

1.用数据库管理工具在界面将表的自动增长标识去除,导完数据,再在界面里改回来。(这种方法麻烦,且要动数据表设置中,不推荐)

2.用set identity_insert off和set identity_insert on(推荐这种方法)

set identity_insert [ database_name . [ schema_name ] . ] table { on | off }
database_name
指定的表所在的数据库的名称。

schema_name
表所属架构的名称。

table
包含标识列的表的名称。

注释
任何时候,一个会话中只有一个表的 identity_insert 属性可以设置为 on。如果某个表已将此属性设置为 on,则对另一个表发出 set identity_insert on 语句时,sql server 将返回一个错误信息,指出 set identity_insert 已设置为 on,并报告已将其属性设置为 on 的表。

如果插入值大于表的当前标识值,则 sql server 自动将新插入值作为当前标识值使用。


set identity_insert 的设置是在执行或运行时设置的,而不是在分析时设置的。

权限
用户必须拥有表,或对表具有 alter 权限。

示例
下面的示例将创建一个包含标识列的表,并说明如何使用 set identity_insert 设置来填充由 delete 语句导致的标识值中的空隙。

复制代码 代码如下:

use adventureworks2012;
go
-- create tool table.
create table dbo.tool(
id int identity not null primary key,
name varchar(40) not null
)
go
-- inserting values into products table.
insert into dbo.tool(name) values ('screwdriver')
insert into dbo.tool(name) values ('hammer')
insert into dbo.tool(name) values ('saw')
insert into dbo.tool(name) values ('shovel')
go


-- create a gap in the identity values.
delete dbo.tool
where name = 'saw'
go

select *
from dbo.tool
go

-- try to insert an explicit id value of 3;
-- should return a warning.
insert into dbo.tool (id, name) values (3, 'garden shovel')
go

-- set identity_insert to on.
set identity_insert dbo.tool on
go

-- try to insert an explicit id value of 3.
insert into dbo.tool (id, name) values (3, 'garden shovel')
go

select *
from dbo.tool
go
-- drop products table.
drop table dbo.tool
go

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网