工作中点滴记录

永远保持学徒心态

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

如果将值插入到表的标识列中,需要启用 SET IDENTITY_INSERT。

举例如下:

创建表Orders、Products,Orders表与Products表分别有标识列OrderID与ProductID:

表Orders,Products
1 CREATE TABLE Orders(
2 OrderID    INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
3 PriceDate DateTime
4 )
5 
6 CREATE TABLE Products(
7 ProductID    INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
8 PriceDate Datetime
9 )


当我们用如下插入语句往Orders表中插入数据:

插入到Orders表
1 INSERT INTO Orders (OrderID ,PriceDate ) VALUES(1,GETDATE())

执行此语句后,会出现如下错误:

把插入语句做如下修改:

修改后的插入语句
1 SET IDENTITY_INSERT Orders ON
2 INSERT INTO Orders (OrderID ,PriceDate ) VALUES(1,GETDATE())

此时执行成功;

我们在向Products表做如上插入:

插入到Products表
1 SET IDENTITY_INSERT Products ON
2 INSERT INTO Products (ProductID,PriceDate ) VALUES(1,GETDATE())

产生如下错误:

我们对sql做如下修改后,products表插入数据成功

 

修改后的sql
1 SET IDENTITY_INSERT Orders ON
2 INSERT INTO Orders (OrderID ,PriceDate ) VALUES(1,GETDATE())
3 SET IDENTITY_INSERT Orders OFF
4 
5 SET IDENTITY_INSERT Products ON
6 INSERT INTO Products (ProductID,PriceDate ) VALUES(1,GETDATE())
7 SET IDENTITY_INSERT Products OFF


可以看到当我们对表的Identity_Insert 的启用与关闭时成对出现,即

成对出现identity_INsert
1 SET IDENTITY_INSERT Products ON
2 --Code
3 SET IDENTITY_INSERT Products OFF


如果我们用下面的语句往Products表中插入数据

View Code
1 SET IDENTITY_INSERT Products ON
2 INSERT INTO Products SELECT * FROM Orders
3 SET IDENTITY_INSERT Products OFF

出现如下错误:

修改上面t-sql语句:

修改后的T-sql
1 SET IDENTITY_INSERT Products ON
2 INSERT INTO Products(ProductID,PriceDate) SELECT * FROM Orders
3 SET IDENTITY_INSERT Products OFF

可以知道如果对标识列进行插入,那么需要显示的列出标识列

posted on 2012-04-09 17:13  梦里故乡  阅读(7440)  评论(0编辑  收藏  举报