Insert Into Table1 Select x, y, z From Table2 其中 x = 1

Insert Into Table1 Select x, y, z From Table2 Where x = 1

在 mssql 中是否可以 运行 这个查询:

Insert Into Table1 Select x, y, z From Table2 Where x = 1

当 Table1 有一个标识列且自动递增时

我收到以下错误:

消息 8101,级别 16,状态 1,第 1 行 table 'table1' 中标识列的显式值只能在使用列列表且 IDENTITY_INSERT 为 ON 时指定。

您必须打开 IDENTITY_INSERT 才能插入身份,完成后将其关闭。这就是语法的样子。

SET IDENTITY_INSERT Table1 ON;

Insert Into Table1 (column1A, column1B, column1C)
    Select Column2A, Column2B, Column2C
       From Table 2
          Where Column2A = 1;

SET IDENTITY_INSERT Table1 OFF;

它应该像

一样简单
Insert Into Table1 (x, y, z)  --<-- Explicitly mention the column names
Select x, y, z 
From Table2 
Where x = 1

您无需在任何地方提及 ID 列,它会自动为您生成标识值并插入到该列中。