0
我想複製同一個表中的多個行並插入到同一個表中,但表中有一個包含主要編號的列。所以,我在插入多個複製行時遇到問題。我無法將最大值設置爲主列(ApplicantExperienceCode
)。複製背後有一個原因,如果申請人想再次申請任何空缺,那麼只需點擊舊的applicationid
,然後所有舊的應用程序體驗數據會自動插入到新的應用程序體驗數據中。如何複製多行並在SQL Server 2012中的主字段中插入同一個表中?
這是我的表結構
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,然後在你的結果上使用一個行號添加最大值來插入你的記錄提交併釋放鎖定... – xQbert
你如何選擇'源'行?你可以在這裏發表你的插入語句嗎?所以我們可以告訴你如何解決它。 – Sparrow
這是一個很好的問題,但被緊急乞討和txtspk寵壞了。請不要在將來的問題中添加這個問題,[請參閱此處](http://meta.stackoverflow.com/q/326569)。謝謝! – halfer