从临时表中删除主键

时间:2017-03-24 14:01:17

标签: tsql

我想使用select into语法创建e临时表。喜欢:

select top 0 * into #AffectedRecord from MyTable

Mytable有一个主键。当我使用merge插入记录时,语法主键是一个问题。我怎么能从临时表中删除pk约束

1 个答案:

答案 0 :(得分:0)

“SELECT TOP(0)INTO ..”技巧很聪明,但我的建议是自己编写表格,原因就像这样。另一方面,当您实际引入数据时,SELECT INTO通常比创建表和执行插入更快。特别是在2014+系统上。

主键的存在与您的问题无关。从另一个表使用SELECT INTO时,不会创建键约束和索引,数据类型和NULLability都可以。请考虑以下代码并注意我的评论:

USE tempdb -- a good place for testing on non-prod servers. 
GO

IF OBJECT_ID('dbo.t1') IS NOT NULL DROP TABLE dbo.t1;
IF OBJECT_ID('dbo.t2') IS NOT NULL DROP TABLE dbo.t2;
GO

CREATE TABLE dbo.t1
(
  id int identity primary key clustered,
  col1 varchar(10) NOT NULL,
  col2 int         NULL
);
GO

INSERT dbo.t1(col1) VALUES ('a'),('b');

SELECT TOP (0) 
  id, -- this create the column including the identity but NOT the primary key
  CAST(id AS int) AS id2, -- this will create the column but it will be nullable. No identity
  ISNULL(CAST(id AS int),0) AS id3, -- this this create the column and make it nullable. No identity.
  col1,
  col2 
INTO dbo.t2
FROM t1;

这是我创建的新表的(为简洁而清理)DDL:

-- New table
CREATE TABLE dbo.t2
(
  id   int IDENTITY(1,1) NOT NULL,
  id2  int               NULL,
  id3  int               NOT NULL,
  col1 varchar(10)       NOT NULL,
  col2 int               NULL
);

请注意,主键已消失。当我带来id as-is时它保留了身份。 将id列强制转换为int(即使它已经是int)是我如何摆脱身份插入 。添加ISNULL是如何使列可以为空。

默认情况下,身份插入设置为off,此查询将失败:     INSERT dbo.t2(id,id3,col1)VALUES(1,1,'x');

Msg 544, Level 16, State 1, Line 39
Cannot insert explicit value for identity column in table 't2' when IDENTITY_INSERT is set to OFF.

设置身份插入将解决问题:

SET IDENTITY_INSERT dbo.t2 ON; 
INSERT dbo.t2 (id, id3, col1) VALUES (1, 1, 'x');

但是现在你必须为该列提供一个值。请注意这里的错误:

INSERT dbo.t2 (id3, col1) VALUES (1, 'x');


Msg 545, Level 16, State 1, Line 51
Explicit value must be specified for identity column in table 't2' either when IDENTITY_INSERT is set to ON

希望这会有所帮助。

侧面说明:这是一种很好的方式来解决选择插入的工作原理。我使用了烫发表,因为它更容易找到。

相关问题