码迷,mamicode.com
首页 > 其他好文 > 详细

SET IDENTITY_INSERT的用法,具体去体验一下

时间:2015-09-11 11:57:34      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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

举例如下:

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

--表Orders,Products
CREATE TABLE Orders(
OrderID    INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
PriceDate DateTime
)

CREATE TABLE Products(
ProductID    INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
PriceDate Datetime
)

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

INSERT INTO Orders (OrderID ,PriceDate ) VALUES(1,GETDATE())

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

技术分享

把插入语句做如下修改:

SET IDENTITY_INSERT Orders ON
INSERT INTO Orders (OrderID ,PriceDate ) VALUES(1,GETDATE())

此时执行成功;

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

SET IDENTITY_INSERT Products ON
INSERT INTO Products (ProductID,PriceDate ) VALUES(1,GETDATE())

产生如下错误:

技术分享

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

--修改后的sql
SET IDENTITY_INSERT Orders ON
INSERT INTO Orders (OrderID ,PriceDate ) VALUES(1,GETDATE())
SET IDENTITY_INSERT Orders OFF

SET IDENTITY_INSERT Products ON
INSERT INTO Products (ProductID,PriceDate ) VALUES(1,GETDATE())
SET IDENTITY_INSERT Products OFF

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

SET IDENTITY_INSERT Products ON
--Code
SET IDENTITY_INSERT Products OFF

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

SET IDENTITY_INSERT Products ON
INSERT INTO Products SELECT * FROM Orders
SET IDENTITY_INSERT Products OFF

出现如下错误:

技术分享

技术分享

修改上面t-sql语句:

SET IDENTITY_INSERT Products ON
INSERT INTO Products(ProductID,PriceDate) SELECT * FROM Orders
SET IDENTITY_INSERT Products OFF

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

SET IDENTITY_INSERT的用法,具体去体验一下

标签:

原文地址:http://www.cnblogs.com/wolfocme110/p/4800294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!