我有我的存儲過程的問題:同時從SQL Server 2的INSERT語句返回SCOPE_IDENTITY
CREATE PROCEDURE [dbo].[Project]
@Code as nvarChar(255) = null,
@Id as nvarChar(255) = null,
@Status as nvarChar(max) = null,
@Project as nvarChar(max) = null,
@ClientSystem as nvarchar(max) = null,
@UserId as bigint = 0,
@ProjectId as bigint = 0,
@ProjectDetailsId bigint = 0 Output
AS
SET NOCOUNT OFF;
IF NOT EXISTS (SELECT [Code]
FROM [dbo].[Project]
WHERE Project.Code = @Code)
BEGIN
INSERT INTO [dbo].[Project]([Code], [Id], [Status], [Project])
VALUES(@Code, @Id, @Status, @Project)
SELECT @ProjectId = SCOPE_IDENTITY()
INSERT INTO [dbo].[ProjectDetails]([FK_ProjectId], [ClientSystem], [UserId])
VALUES(@ProjectId, @ClientSystem, @UserId)
SELECT @ProjectDetailsId = SCOPE_IDENTITY()
END
ELSE
BEGIN
SELECT [ProjectId] AS 'ProjectId'
FROM [dbo].[Project]
WHERE Project.Code = @Code
END
我要回來自Insert
聲明Scope_Identity
並通過第一次插入的值作爲參數傳遞給第二插入並返回2nd Insert語句的Scope_Identity
。
我得到的錯誤是當我得到的第一個Insert
的身份,在特定表中的身份增加2倍,如在數據庫表中它將被插入2但在編碼它將返回1。給其他插入它給予衝突。
你的代碼看起來確定我要插入不同的是你的'@ProjectId因爲bigint = 0,'不是'輸出'參數 – ughai
非常好的問題,upvote –
@ughai不,這不是原因。原因是'SCOPE_IDENTITY()'返回最後一個插入的值,而不管它發生在何處。因此,當第二個插入正在運行** parallel **時,對'SCOPE_IDENTITY()'的調用將從另一個並行運行過程返回值。 –