我正在创建一堆用于在数据库中添加,更新和删除的存储过程我正在为学校做一个项目。我想使用try catch和一个标志告诉用户是否成功。我正在使用SQL Server 2005,我有基本的存储过程,但想要添加它以使我的项目更好。我一直在关键字集附近得到一个SQL错误不正确的语法。 这是我的代码:
CREATE PROCEDURE dbo.addCustomer
-- Add the parameters for the stored procedure here
@flag bit output, --return 1 for success and 0 for fail
@Customer_ID varchar(50),
@sales_region varchar(50),
@Items_Recieved varchar(max),
@Hual_ID varchar(50)
AS
BEGIN
BEGIN TRANSACTION
BEGIN TRY
INSERT into dbo.Customer(Customer_ID,Sales_region, Items_Recieved, Hual_ID)
values(@Customer_ID,@sales_region, @Items_Recieved, @Hual_ID
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
任何人都可以指出我正确的方向,我确信我做了一些简单的错误,或者忘了做某事。 感谢。
答案 0 :(得分:2)
CREATE PROCEDURE dbo.addCustomer
-- Add the parameters for the stored procedure here
@flag bit output, --return 1 for success and 0 for fail
@Customer_ID varchar(50),
@sales_region varchar(50),
@Items_Recieved varchar(max),
@Hual_ID varchar(50)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO dbo.Customer(Customer_ID,Sales_region, Items_Recieved, Hual_ID)
VALUES(@Customer_ID,@sales_region, @Items_Recieved, @Hual_ID)
COMMIT TRANSACTION;
SET @flag=1;
END TRY
BEGIN CATCH
IF (@@TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION;
END
SET @flag=0;
-- Utilise your other Error Functions to get detailed
-- Information about the Error, function like
-- ERROR_LINE(), ERROR_MESSAGE(), ERROR_NUMBER()....
END CATCH
END
GO