SQL 事物


/*
创建表*/ 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' 备份表存储过程

 

 

posted @ 2013-10-05 22:14  大叔123  阅读(348)  评论(0编辑  收藏  举报