/*建立表*/ CREATE TABLE a ([id] int IDENTITY(1,1) PRIMARY KEY , [Name] varchar(50) ) CREATE TABLE B ( [id] int IDENTITY(1,1) PRIMARY KEY, [Type] varchar(50), [aid] int Foreign key ([aid]) references a(ID) ) --建立存儲過程 CREATE PROCEDURE [dbo].[ADD] (@strName varchar(50), @strType varchar(50)) as DECLARE @aid int begin tran begin try INSERT INTO A ([name]) VALUES (@strName) --DECLARE @aid int=SELECT IDENT_SEED('A') INSERT INTO B ([type],[aid]) VALUES(@strType,@@identity) end try begin catch if @@trancount > 0 rollback tran end catch if @@trancount > 0 commit tran --執行存儲過程 EXEC [ADD] 'fff','fff' --查詢結果 SELECT * FROM A SELECT * FROM b
--1. 在事務語句最前面加上set xact_abort on set xact_abort on begin tran update statement 1 ... update statement 2 ... delete statement 3 ... commit tran go
--2. 在每一個單獨的DML語句執行後,當即判斷執行狀態,並作相應處理。 begin tran update statement 1 ... if @@error <> 0 begin rollback tran goto labend end delete statement 2 ... if @@error <> 0 begin rollback tran goto labend end commit tran labend: go
--3. 在SQL Server 2005中,可利用 try...catch 異常處理機制 begin tran begin try update statement 1 ... delete statement 2 ... end try begin catch if @@trancount > 0 rollback tran end catch if @@trancount > 0 commit tran go
set xact_abort on --開啓默認系統事物 非自定義錯誤回滾 begin tran ----------------------------------- declare @tbname nvarchar(100) declare @create nvarchar(500) declare cur1 cursor for select name from sysobjects where xtype='U' AND ( charindex('louxiqu',name)>0 OR charindex('louxinqu',name)>0 ) OPEN cur1 fetch cur1 into @tbname while @@FETCH_STATUS = 0 BEGIN -------------------------- if object_id('MCJZYFDATA.dbo.'+@tbname) is not null BEGIN if object_id('Bak_MCJZYFDATA.dbo.'+@tbname) is not null BEGIN EXEC(' DROP TABLE Bak_MCJZYFDATA.dbo.'+@tbname+'' ); END SET @create=' SELECT * INTO Bak_MCJZYFDATA.dbo.'+@tbname+' from MCJZYFDATA.dbo.'+@tbname EXEC(@create); EXEC(' DROP TABLE MCJZYFDATA.dbo.'+@tbname+'' ); --print @create END -------------------------- fetch cur1 INTO @tbname end close cur1 deallocate cur1 ----------------------------------- commit tran go ------------------- ALTER Proc [dbo].[BakTable]( @tbname Nvarchar(500) ) as Declare @sql Nvarchar(2000) Declare @baktbname Nvarchar(500) SET @baktbname=@tbname+replace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),' ',''),':','') SET @sql=' SELECT * INTO Bak_MCJZYFDATA.dbo.'+@baktbname+' from MCJZYFDATA.dbo.'+@tbname exec(@sql) --exec BakTable 'Config' 備份表存儲過程