以下是存储过程的代码。
代码的第一部分按预期工作。它接受变量,INSERT进入一个表,然后使用从该动作创建的主键在单独的表上执行另一个INSERT。
然而,未发生的是if / else if / else块中的代码然后结束。它基本上应该检查以确保两个ID列正确匹配。如果没有,它会将列调整为适当的值,然后返回旧值以及创建条目的人员的日期和用户名(lastChangeOperator)。
我花了一整天时间写这个和这个程序的另一部分,所以我希望第二组眼睛能够做到这一点。
ALTER PROCEDURE [dbo].[sp_AgentIdAprCheck]
(
@companyCode char(3),
@agentId char(10),
@firstName nvarChar(50),
@lastname nvarChar(50),
@suffix char(10),
@ssn int,
@taxIdType char(1),
@entityType char(1),
@corporateName nvarChar(100),
@currentUniqueId int OUTPUT,
@currentAgentId int OUTPUT,
@operator nvarchar(50) OUTPUT,
@date datetime OUTPUT
)
AS
DECLARE @rows int = 0
DECLARE @uniqueAgentId int = 0
DECLARE @lastChangeOperator char(6) = 'LVOMQ1'
DECLARE @LastChangeDate datetime
--DECLARE @currentUniqueId int = 0
--DECLARE @currentAgent int = 0
--DECLARE @operator nvarchar(50)
--DECLARE @date datetime
SELECT @rows = COUNT(AgentTaxId)
FROM AgentIdentification
WHERE AgentTaxId = @ssn
if @rows > 0
return 1
else
BEGIN TRANSACTION
SET @LastChangeDate = GETDATE()
INSERT INTO Agent (EntityType, FirstName, LastName,
NameSuffix, CorporateName, LastChangeOperator, LastChangeDate)
VALUES (@entityType, @firstName, @lastname,
'', @corporateName, @lastChangeOperator, @LastChangeDate)
SELECT @uniqueAgentId = @@IDENTITY
SELECT UniqueAgentId
FROM Agent
INSERT INTO AgentIdentification (UniqueAgentId, TaxIdType,
AgentTaxId, LastChangeOperator, LastChangeDate)
VALUES (@uniqueAgentId, @taxIdType, @ssn, @
lastChangeOperator, @lastChangeDate)
DECLARE @uniqueIdRows int = 0
SELECT @uniqueIdRows = COUNT(UniqueAgentId)
FROM UniqueAgentIdToAgentId
WHERE UniqueAgentId = @uniqueAgentId
DECLARE @agentIdRows int = 0
SELECT @agentIdRows = COUNT(AgentId)
FROM UniqueAgentIdToAgentId
WHERE AgentId = @agentId
if @uniqueIdRows = 0 AND @agentIdRows = 0
BEGIN
INSERT INTO UniqueAgentIdToAgentId (UniqueAgentId, AgentId,
CompanyCode, LastChangeOperator, LastChangeDate)
VALUES (@uniqueAgentId, @agentId, @companyCode,
@lastChangeOperator, @LastChangeDate)
END
else if @agentIdRows = 0
BEGIN
SELECT @currentUniqueId = UniqueAgentId,
@operator = LastChangeOperator, @date = @LastChangeDate
FROM UniqueAgentIdToAgentId
UPDATE UniqueAgentIdToAgentId
SET UniqueAgentId = @uniqueAgentId
WHERE AgentId = @agentId AND UniqueAgentId = @currentUniqueId
END
else
BEGIN
SELECT @currentAgentId = AgentId,
@operator = LastChangeOperator, @date = @LastChangeDate
FROM UniqueAgentIdToAgentId
UPDATE UniqueAgentIdToAgentId
SET AgentId = @agentId
WHERE UniqueAgentId = @uniqueAgentId --AND AgentId = @currentAgentId
return 2
END
COMMIT TRANSACTION
答案 0 :(得分:1)
您是否尝试过使用SCOPE_IDENTITY()
代替@@IDENTITY
?我猜这可能是你的问题。
Pinal Dave说here
*“为避免以后与添加触发器相关的潜在问题,请始终使用SCOPE_IDENTITY()返回T SQL语句或存储过程中最近添加的行的标识。”*