如何在 SQL 中为临时表添加标识列?

goo*_*yui 2 t-sql sql-server

如何在 SQL 中为临时表添加标识列?

当 IDENTITY_INSERT 设置为 ON 或复制用户插入 NOT FOR REPLICATION 标识列时,必须为表“#T”中的标识列指定显式值。

我收到以下块的 SQL 语法错误。

 if object_id('tempdb.dbo.#t') is not null  
   drop table #t

create table #t
(
  [ID] [int] IDENTITY(1,1) NOT NULL,
  [TotalCount] int,
  [PercentageComplete] nvarchar(4000)
)

insert into #t
  select totalcount, percentagecomplete from table_a
Run Code Online (Sandbox Code Playgroud)

Sah*_*rsh 6

在表声明后将其添加到您的查询中

SET IDENTITY_INSERT #t OFF 
Run Code Online (Sandbox Code Playgroud)

这应该可以解决它。以下代码在我的机器上运行

CREATE TABLE #t
(
    [ID] [INT] IDENTITY(1,1) NOT NULL,
    [TotalCount] INT,
    [PercentageComplete] NVARCHAR(4000)
)

SET IDENTITY_INSERT #t OFF 

INSERT INTO #t
    SELECT
        totalcount, percentagecomplete 
    FROM
        table_a
Run Code Online (Sandbox Code Playgroud)