如何复制多行并在SQL Server 2012中插入与主字段相同的表?

时间:2016-11-29 19:40:07

标签: sql-server sql-server-2012

我想从同一个表中复制多行并插入到同一个表中,但是表中有一个包含主编号的列。所以,我在插入多个副本行时遇到问题。我无法将maxvalue设置为主列(ApplicantExperienceCode)。复制背后的原因是,如果申请人想要在任何空缺中再次申请,那么只需点击旧的applicationid,然后所有旧的应用程序体验数据自动插入到新的应用程序体验数据中。

这是我的表结构

CREATE TABLE [dbo].[ApplicantExperience]
(
    [ApplicantExperienceCode] [bigint] NOT NULL,
    [ApplicationId] [bigint] NOT NULL,
    [DesignationAndPlaceOfPosting] [varchar](250) NOT NULL,
    [NameOfOrganization] [varchar](250) NOT NULL,
    [PayScaleCode] [smallint] NOT NULL,
    [PeriodFrom] [date] NOT NULL,
    [PeriodTo] [date] NOT NULL,
    [ReportingToDesignation] [varchar](250) NULL,
    [RelevantExperienceDetails] [varchar](500) NULL,
    [SelfDeclarationExpCode] [tinyint] NULL,
    [ActionCode] [tinyint] NOT NULL,
    [TransactionByCode] [int] NOT NULL,
    [TransactionDate] [datetime] NOT NULL,
    [TransactionIp] [varchar](23) NOT NULL,

    CONSTRAINT [PK_ApplicantExperience] 
        PRIMARY KEY CLUSTERED ([ApplicantExperienceCode] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

我的插入查询

    insert into ApplicantExperience
select * from ApplicantExperience where ApplicationId=5

错误消息是

Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK_ApplicantExperience'. Cannot insert duplicate key in object 'dbo.ApplicantExperience'. The duplicate key value is (7).
The statement has been terminated.

1 个答案:

答案 0 :(得分:0)

试试这个:

        INSERT into ApplicantExperience
            SELECT 
                ApplicantExperienceCode = ROW_NUMBER()OVER(ORDER BY ApplicationId) 
                   + COALESCE((SELECT MAX(ApplicantExperienceCode) FROM ApplicantExperience), 0)
                ,ApplicationId, DesignationAndPlaceOfPosting, NameOfOrganization, PayScaleCode, PeriodFrom, PeriodTo, ReportingToDesignation, RelevantExperienceDetails, SelfDeclarationExpCode, ActionCode, TransactionByCode, TransactionDate, TransactionIp
            from ApplicantExperience 
            where ApplicationId=5