我有一个永远不会返回错误的mssql代码。以下是代码:
alter proc USP_Havale
@GonderenID int,
@AliciID int,
@GonderilenPara money
as
begin try
begin transaction
update Hesap set
Para = Para - @GonderilenPara
where HesapID = @GonderenID
update Hesap set
Para = Para + @GonderilenPara
where HesapID = @AliciID
commit tran
end try
begin catch
rollback tran
print 'error'
end catch
我运行的代码如下:
exec USP_Havale @GonderenID=1,@AliciID=5,@GonderilenPara=1500
问题是id 5不存在。因此代码应返回false并打印错误'。相反,它返回以下内容:
1 row(s) affected.
0 row(s) affected.
这里有什么问题?
答案 0 :(得分:2)
这是因为你的sp中有一个简单的更新语句,如果传递的id不存在你就不会引发错误,因此它很简单地尝试更新id = 5且没有行更新的行它不是一个错误,它只是命令没有更新任何行。
如果您希望存储过程引发错误,如果传递的id不存在,那么您需要在catch块中显式引发错误,这将使您的控件跳转到catch块,类似这样...... < / p>
ALTER PROCEDURE USP_Havale
@GonderenID int,
@AliciID int,
@GonderilenPara money
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
-- do a check here before executing update statements
IF NOT EXISTS (SELECT 1
FROM Hesap
WHERE HesapID = @AliciID)
BEGIN
RAISERROR('Error id does not exist',16,1)
END
-- if test passes now open transaction and do your stuff
BEGIN TRANSACTION
update Hesap
set Para = Para - @GonderilenPara
where HesapID = @GonderenID
update Hesap
set Para = Para + @GonderilenPara
where HesapID = @AliciID
COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- Now since the error can happen even before
-- you open a transaction add this check
IF (@@TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION
END
PRINT 'error'
END CATCH
END
答案 1 :(得分:1)
在每个UPDATE
语句后,您可以添加下一个检查:
IF @@ROWCOUNT = 0
RAISERROR('@GonderenID and/or @AliciID doesn't exist.', 16, 1);