SQL IDENTITY INSERT问题

时间:2017-05-30 10:39:46

标签: sql-server

你能帮忙吗?

我正在运行以下查询:

set identity_insert sites_dynamic ON 

insert into sites_dynamic
    select * 
    from gpbatt_archive.dbo.sites_dynamic 
    where site_serial_number = 49955

set identity_insert sites_dynamic OFF 

set identity_insert sites_static ON 

insert into sites_static
    select * 
    from gpbatt_archive.dbo.sites_static 
    where static_site_id in (select static_site_id 
                             from gpbatt_archive.dbo.sites_dynamic 
                             where site_serial_number = 49955)

set identity_insert sites_static OFF 

返回的错误是:

  

Msg 8101,Level 16,State 1,Line 3
  只有在使用列列表并且IDENTITY_INSERT为ON时,才能指定表'sites_dynamic'中标识列的显式值。

任何人都可以帮助我吗?我是这个新手

1 个答案:

答案 0 :(得分:4)

使用set identity_insert <tablename> on时,insert语句必须包含列列表。

这是正确的方法:

set identity_insert targetTable on

insert into targetTable (col1, col2 [, coln])
select col1, col2 [, coln]
from sourceTable

set identity_insert targetTable off

由Nick.McDermaid评论 - 始终包含列列表的最佳做法。