在SQL Server中克隆/复制记录,并自动增加ID

时间:2014-06-02 15:43:19

标签: sql sql-server

我想用registry_id = 1复制所有行,并且克隆行的id应自动递增。

执行时

insert into [ZAC2].[dbo].[rubrics] 
  ([reference]
  ,[name_de]
  ,[name_fr]
  ,[name_en]
  ,[name_es]
  ,[registry_id]
  ,[registry_type]
  ,[parent_id]
  ,[created_at]
  ,[updated_at]
  ,[creator_id]
  ,[updater_id]
  ,[level]
  ,[inherited_rating]
  ,[has_children])
select ([reference]
  ,[name_de]
  ,[name_fr]
  ,[name_en]
  ,[name_es]
  ,[registry_id]
  ,[registry_type]
  ,[parent_id]
  ,[created_at]
  ,[updated_at]
  ,[creator_id]
  ,[updater_id]
  ,[level]
  ,[inherited_rating]
  ,[has_children]
FROM [ZAC2].[dbo].[rubrics] 
  where registry_id=1

我收到错误消息:

  

无法在对象'dbo.rubrics'中插入具有唯一索引'idx_rubrics_reference_registry'的重复键行。重复键值为(0,1,RegistryPlan)。

Script Keys as > Create To > New Query Editor Window我得到:

ALTER TABLE [dbo].[rubrics] 
ADD PRIMARY KEY CLUSTERED ([id] ASC)
    WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, 
          IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, 
          ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80
) ON [PRIMARY]

Script Table as > Insert To > New Query Editor Window我得到:

(<reference, varchar(255),>
           ,<rating, varchar(1),>
           ,<name_de, varchar(255),>
           ,<name_fr, varchar(255),>
           ,<name_en, varchar(255),>
           ,<name_es, varchar(255),>
           ,<registry_id, int,>
           ,<registry_type, varchar(255),>
           ,<parent_id, int,>
           ,<created_at, datetime,>
           ,<updated_at, datetime,>
           ,<creator_id, int,>
           ,<updater_id, int,>
           ,<level, int,>
           ,<inherited_rating, varchar(1),>
           ,<has_children, bit,>)

1 个答案:

答案 0 :(得分:0)

@marc_s你是绝对正确的,我没有正确阅读错误信息。 idx_rubrics_reference_registry具有唯一约束,因此无法复制行。我更改了它(事实上我的插入方法与另一个id为参考注册表),现在它工作。非常感谢!