https://www.cnblogs.com/MuNet/archive/2013/02/27/5563411.html
1、创建带 Try Catch 的存储过程模板
Copy下面的代码,然后新建查询,就可以写sql语句,执行完后,一个你自己的存储过程就建立好了!
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- AUTHOR: -- DESCRIBE: -- ============================================= CREATE PROCEDURE [dbo].[UP_InsertJHBData] --存储过程名 @CustomerName VARCHAR(50) --参数 AS BEGIN SET NOCOUNT ON --提高性能的,必须要有 DECLARE @Now DATETIME SET @Now = GETDATE() --所有操作保证统一时间 BEGIN TRY --在这里写SQL END TRY BEGIN CATCH DECLARE @ErrorMessage NVARCHAR(4000) ; DECLARE @ErrorSeverity INT ; DECLARE @ErrorState INT ; SELECT @ErrorMessage = ERROR_MESSAGE() , @ErrorSeverity = ERROR_SEVERITY() , @ErrorState = ERROR_STATE() ; PRINT @ErrorMessage RAISERROR(@ErrorMessage, -- Message text. @ErrorSeverity, -- Severity. @ErrorState -- State. ) ; RETURN -1 ; END CATCH END
2、创建带事务的存储过程模板
将带 Try Catch 的存储过程的模板中加入了事务的控制
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- AUTHOR: -- DESCRIBE: -- ============================================= CREATE PROCEDURE [dbo].[UP_InsertJHBData] --存储过程名@CustomerName VARCHAR(50) --参数 AS BEGIN SET NOCOUNT ON ;--提高性能的,必须要有 DECLARE @Now DATETIME ; SET @Now = GETDATE() ;--所有操作保证统一时间 BEGIN TRY BEGIN TRANSACTION myTrans ;--开始事务 --在这里写SQL COMMIT TRANSACTION myTrans ;--事务提交语句 END TRY BEGIN CATCH ROLLBACK TRANSACTION myTrans-- 始终回滚事务 --抛出异常 DECLARE @ErrorMessage NVARCHAR(4000) ; DECLARE @ErrorSeverity INT ; DECLARE @ErrorState INT ; SELECT @ErrorMessage = ERROR_MESSAGE() , @ErrorSeverity = ERROR_SEVERITY() , @ErrorState = ERROR_STATE() ; RAISERROR(@ErrorMessage, -- Message text. @ErrorSeverity, -- Severity. @ErrorState -- State. ) ; END CATCH END
3、循环模板
在存储过程中,经常会生成一些临时表,然后循环临时表的数据进行处理,以下模板可以帮助伙伴们快速处理此类需求
--生成带行号的临时表数据,并插入临时表#T_Table中 SELECT ROW_NUMBER() OVER (ORDER BY ID) AS RowNum,NAME INTO #T_Table FROM TableName --获取记录总数 DECLARE @RecordCount INT = 0 SELECT @RecordCount = COUNT(1) FROM #T_Table DECLARE @CurrRowNum INT = 1 --当前行号 DECLARE @CurrName VARCHAR(50) --当前字段 --循环记录 WHILE @CurrRowNum <= @RecordCount BEGIN --获取当前记录 SELECT @CurrName = Name FROM #T_Table WHERE RowNum = @CurrRowNum --自定义sql SET @CurrRowNum = @CurrRowNum + 1 --到下一条记录 END
分类: Sql Server
来源:CSDN
作者:qq_18932003
链接:https://blog.csdn.net/qq_18932003/article/details/103473749