CREATE PROCEDURE sp_BOOKEDVEHICLES
@flag bit output,-- return 0 for fail,1 for success
@REGISTRATIONID varchar(30),
@VEHICLEID varchar(9),
@VEHICLENAME varchar(20)
AS
BEGIN
BEGIN TRANSACTION
BEGIN TRY
Insert into BST_TVL_BOOKED_VEHICLES_TB(REGISTRATIONID, VEHICLEID, VEHICLENAME) Values(@REGISTRATIONID,@VEHICLEID,@VEHICLENAME)
set @flag=1;
IF @@TRANCOUNT > 0
BEGIN commit TRANSACTION;
END
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN rollback TRANSACTION;
END
set @flag=0;
END CATCH
END
GO
Declare @flag bit
EXEC sp_BOOKEDVEHICLES @flag output,
@REGISTRATIONID = '2364',
@VEHICLEID = '27',
@VEHICLENAME = 'Ford'
if @flag=1
print 'Successfully inserted'
else
print 'There is some error'
显然,代码中有错误,但我找不到它...无法使用stord程序插入数据。
它向我显示了这个错误:(0行受影响)有一些错误。
答案 0 :(得分:0)
Insert into BST_TVL_BOOKED_VEHICLES_TB(REGISTRATIONID, VEHICLEID, VEHICLENAME) Values(@REGISTRATIONID,@VEHICLEID,@VEHICLENAME)
set @flag=1;
IF @@TRANCOUNT > 0
BEGIN commit TRANSACTION;
END
这必须抛出SQL异常,因为@flag <> 1
。试试print ERROR_MESSAGE()
以获得实际错误的描述?
答案 1 :(得分:0)
好的,你正在混淆一些概念。
1 - 当您希望多个语句提交或回滚时使用事务。
例如,从客户帐户和信用卡供应商处扣款。提交或回滚。
2 - 由于您没有这个条件,只需用TRY / CATCH包装插入。
请参阅我的博客,了解错误处理的方法。
http://craftydba.com/?tag=error-handling
3 - 程序可以返回一个值。为什么不是零,如果好,一个如果坏。
我重写了你的代码如下。
--
-- Re-write of code
--
CREATE PROCEDURE sp_BOOKEDVEHICLES
@REGISTRATIONID varchar(30),
@VEHICLEID varchar(9),
@VEHICLENAME varchar(20)
AS
BEGIN
-- TRY TO ADD A RECORD
BEGIN TRY
INSERT INTO BST_TVL_BOOKED_VEHICLES_TB
(REGISTRATIONID, VEHICLEID, VEHICLENAME)
VALUES
(@REGISTRATIONID, @VEHICLEID, @VEHICLENAME);
RETURN 0;
END TRY
-- CATCH ERROR
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
RETURN 1;
END CATCH
END
GO
-- Sample call
DECLARE @RETCODE INT
EXEC @RETCODE = sp_BOOKEDVEHICLES
@REGISTRATIONID = '2364',
@VEHICLEID = '27',
@VEHICLENAME = 'Ford';
-- Just show the result.
IF @RETCODE = 1
PRINT 'BAD INSERT CALL'
ELSE
PRINT 'GOOD INSERT CALL';
请测试代码,因为我没有定义您的表格...