我通常会这样做:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[procedure_name]') AND ObjectProperty(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[procedure_name]
GO
CREATE PROCEDURE [dbo].[procedure_name]
(
@param1 VARCHAR(100)
,@param2 INT
)
AS
/*
*******************************************************************************
<Name>
[procedure_name]
</Name>
<Purpose>
[Purpose]
</Purpose>
<Notes>
</Notes>
<OutsideRef>
Called From: [Called From]
</OutsideRef>
<ChangeLog>
Change No: Date: Author: Description:
_________ ___________ __________ _____________________________________
001 [DATE] [YOU] Created.
</ChangeLog>
*******************************************************************************
*/
BEGIN
SET NOCOUNT ON
SET XACT_ABORT OFF -- Allow procedure to continue after error
-- *****************************************
-- Parameter string. Used for error handling
-- *****************************************
DECLARE @ErrorNumber INT
,@ErrorMessage VARCHAR(400)
,@ErrorSeverity INT
,@ErrorState INT
,@ErrorLine INT
,@ErrorProcedure VARCHAR(128)
,@ErrorMsg VARCHAR(2000)
,@NestedProc BIT = 1
,@Params VARCHAR(255); -- String representing parameters, make it an appropriate size given your parameters.
--Be Careful of the CONVERT here, GUIDs (if you use them) need 36 characters, ints need 10, etc.
SET @Params = ''
+ CHAR(13) + '@param1 = ' + COALESCE(CONVERT(VARCHAR(100), @param1), 'NULL')
+ CHAR(13) + '@param2 = ' + COALESCE(CONVERT(VARCHAR(10), @param2), 'NULL')
BEGIN TRY
--If you're using transactions, and want an 'all or nothing' approach, use this so that
--you only start a single transaction in the outermost calling procedure (or handle
--that through your application layer)
IF @@TRANCOUNT = 0
BEGIN
SET @NestedProc = 0
BEGIN TRANSACTION
END
INSERT INTO [TABLE]
(
COL1
,COL2
)
VALUES
(
@param1
,@param2
);
--Commit the transaction if this is the outtermost procedure and if there is a transaction to rollback.
IF @@TRANCOUNT > 0 AND @NestedProc = 0
BEGIN
COMMIT TRANSACTION
END
END TRY
BEGIN CATCH
--Roll back the transaction if this is the outtermost procedure and if there is a transaction to rollback.
IF @@TRANCOUNT > 0 AND @NestedProc = 0
BEGIN
ROLLBACK TRANSACTION
END
-- Execute the error retrieval routine.
SELECT
@ErrorNumber = ERROR_NUMBER(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorProcedure = ERROR_PROCEDURE(),
@ErrorState = ERROR_STATE(),
@ErrorLine = ERROR_LINE(),
@ErrorMessage = ERROR_MESSAGE();
SET @ErrorMsg = 'Error Number : ' + CAST(@ErrorNumber AS VARCHAR(5)) + CHAR(13)
+ 'Procedure Name : ' + @ErrorProcedure + CHAR(13)
+ 'Procedure Line : ' + CAST(@ErrorLine AS VARCHAR(5)) + CHAR(13)
+ 'Error Message : ' + @ErrorMessage + CHAR(13)
+ 'Parameters : ' + CHAR(13) + @Params + CHAR(13);
--Raise the exception.
RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState);
END CATCH
END
GO
这种类型的过程允许您使用事务嵌套过程(只要期望的效果是,如果在任何地方抛出错误,您最终会返回到外部过程然后回滚)。我认为这个模板无法处理的一个非常重要的场景是抛出一个严重到足以完全终止该过程的错误的情况。也许其他人可以在这方面插话。