Sql server SQL返回错误的@标识
我有以下SQL Server存储过程:Sql server SQL返回错误的@标识,sql-server,Sql Server,我有以下SQL Server存储过程: CREATE procedure [dbo].[sp_FinancialInstitutionsAdd] @Name varchar(50) AS set nocount on begin tran declare @retval int = 0 declare @rmdID int execute @rmdID = dbo.sp_MetaDataRecsAdd
CREATE procedure [dbo].[sp_FinancialInstitutionsAdd]
@Name varchar(50)
AS
set nocount on
begin tran
declare @retval int = 0
declare @rmdID int
execute @rmdID = dbo.sp_MetaDataRecsAdd
select @rmdID as rmdID
if @@ERROR <> 0
begin
rollback tran
return -1
end
insert FinancialInstitutions (Name, rmdID)
values (@Name, @rmdID)
if @@ERROR <> 0
begin
rollback tran
return -1
end
return scope_identity()
commit tran
我只能获取插入的MetaDataRecs表的ID,但需要FinicalInstitutions表的ID。当直接在SQL中执行时,该过程可以正常工作,但当使用代码中的ExecuteScalar命令执行时,则无法正常工作 @@identity和scope\u标识都将返回上次创建的id。 对于使用触发器将某些内容插入另一个表的人来说,这也是一个问题 我不知道你的桌子,但我想
declare @id int
select @id = max(id) from FinancialInstitutions
return @id
干杯首先,除非您使用的是非常旧的sql server版本,否则如果@@ERROR 0,您应该使用它而不是旧的样式。Sql server自2005年版本起支持Try…catch。 其次,我怀疑您从scope_Identity函数中获得了错误的标识,因为它未包含在事务中。我不确定如果事务回滚,它应该返回什么。 试试这个:
CREATE procedure [dbo].[sp_FinancialInstitutionsAdd]
(
@Name varchar(50),
@ReturnValue int output
)
AS
set nocount on
declare @rmdID int,
@retval int = 0
begin Try
begin tran
execute @rmdID = dbo.sp_MetaDataRecsAdd
-- select @rmdID as rmdID -- What is that row? I've commented it out since it makes no sense to me
insert into FinancialInstitutions (Name ,rmdID)
values (@Name ,@rmdID)
set @ReturnValue = scope_identity()
commit tran
end try
begin catch
rollback tran
end catch
注1:您需要更改对此过程的调用,以添加@ReturnValue作为输出参数
注2:如果此过程在此行设置@ReturnValue=scope_identity之前遇到错误,@ReturnValue的值将保持为DBNull.value
据我所知,你是依靠旧的方法处理错误。
尝试使用Try..CATCH块以提高可读性和良好的设计实践
另外,不要使用RETURN将标识值返回给调用方,最好的做法是为此声明输出参数
否决理由:这个答案是错误的。Scope_identity将返回在其中执行的作用域中的最后一个标识。如果触发器在存储过程中执行,它将不会返回由触发器创建的标识。你在投票前试过吗?是吗?阅读我链接的文章。它之所以被称为scope_identity是有原因的。@identity和scope\u identity.Side注意:存储过程不应使用sp\u前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用sp_u,并使用其他东西作为前缀——或者根本不使用前缀!当从sql查询运行此过程时,它工作正常。当它与executescalar一起运行时,它返回null。但是表会更新,这是因为它不会返回过程的返回值,而是select语句返回的第一个值或行。您的过程中没有select语句。请参阅我编辑的答案。替换set@ReturnValue=scope_identity@kunstena我不理解你最后的评论。另外,请接受marc_的建议-不要将sp_用作存储过程的前缀+投票理由:这个答案没有添加任何我在回答中没有提到的信息,在你发布你的答案前6个小时。