Tsql sql从临时表中删除主键

Tsql sql从临时表中删除主键,tsql,Tsql,我想使用select into语法创建e temp表。比如: select top 0 * into #AffectedRecord from MyTable Mytable有一个主键。当我使用merge-into-syntax主键插入记录时,可能会出现问题。我如何才能将pk约束从临时表中删除,并将选择前0名放入。。这个技巧很聪明,但我的建议是,出于这样的原因,自己编写表格。另一方面,当您实际引入数据时,SELECT INTO通常比创建表和执行insert更快。特别是在2014+系统上 主键的

我想使用select into语法创建e temp表。比如:

select top 0 * into #AffectedRecord from MyTable

Mytable有一个主键。当我使用merge-into-syntax主键插入记录时,可能会出现问题。我如何才能将pk约束从临时表中删除,并将选择前0名放入。。这个技巧很聪明,但我的建议是,出于这样的原因,自己编写表格。另一方面,当您实际引入数据时,SELECT INTO通常比创建表和执行insert更快。特别是在2014+系统上

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

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列强制转换为int,即使它已经是int,这就是我摆脱标识插入的方法。添加ISNULL是如何使列可为null的

默认情况下,此处的identity insert设置为off,以确保此查询失败: 插入dbo.t2id,id3,col1值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.
将identity insert设置为on将解决此问题:

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
希望这能有所帮助


另请注意:这是一种很好的方法,可以用来玩弄和理解select insert的工作原理。我用了烫发台,因为它更容易找到

你说的是身份PK吗?如果是,请查看:。没有必要放弃约束。我不能使用这个。错误消息:只有在使用列列表且“identity_INSERT”处于启用状态时,才能为表“AffectedRecord”中的identity列指定显式值。我建议您实际查看identity_INSERTIt,这将有助于了解您打算执行的操作。删除任何id列都是非常危险的,如果在不考虑所有影响的情况下删除,可能会导致许多其他事情。我的目的是确保我们作为一个社区向你们建议最好的前进方向,同时确保我们不会无意中给你们自己造成更多的问题。非常感谢。我将手动创建表。我放弃了选择