日期:2014-05-18  浏览次数:20502 次

请教关于数据操作回滚的问题
SQL code

CREATE TABLE tb1 
(id1 INT,
id2 DECIMAL(4, 1))

INSERT INTO tb1
SELECT 1, 4.3
UNION ALL
SELECT 2, 234.2 

现在把字段id2的数据类型改为decimal(4,2),数据库生成脚本如下:

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_tb1
    (
    id1 int NULL,
    id2 decimal(4, 2) NULL 
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_tb1 SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.tb1)
     EXEC('INSERT INTO dbo.Tmp_tb1 (id1, id2)
        SELECT id1, id2 FROM dbo.tb1 WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.tb1
GO
EXECUTE sp_rename N'dbo.Tmp_tb1', N'tb1', 'OBJECT' 
GO
COMMIT

如果这样执行操作,数据将会丢失,因为有数据溢出。

问题:
语句中的回滚操作怎么不生效呢?还是说回滚对这类操作无效呢?求教执行这类操作时如果进行数据回滚



------解决方案--------------------
直接 alter table tb1 alter column id2 DECIMAL(4, 2) 溢出就会终止语句
------解决方案--------------------
事务里面加上set xact_abort on
------解决方案--------------------
SQL code

CREATE TABLE tb1 
(id1 INT,
id2 DECIMAL(4, 1))

INSERT INTO tb1
SELECT 1, 4.3
UNION ALL
SELECT 2, 234.2 


begin try
 begin tran
   alter table tb1 alter column id2 DECIMAL(4, 2)
 commit tran
end try
begin catch
  rollback tran
  select error_number() as error_number ,
         error_message() as error_message,
         error_state() as error_state,
         error_severity() as error_severity
end catch 
 
error_number error_message                                                         error_state error_severity
------------ --------------------------------- ----------- --------------
8115         Arithmetic overflow error converting numeric to data type numeric.         8           16

(1 row(s) affected)