开发者

Are schema modifying commands transactional?

For example, if I drop a table then roll back the transaction is the table recreated?

What are the limits to the schema changes that can be made in a transaction?

If the above depends on the version of Sql Server, please say so...

Background

I am thinking of using some “select into” statements to create tables and then need to drop ALL the above tables as a later part of the workflow.

None of开发者_StackOverflow the table will have more then a few tens of rows.


Most database object DDL statements can be part of an user transaction. Some exceptions exists, like operations that related to files of the database itself (like ALTER DATABASE ... ADD/REMOVE FILE). At the server level again, most objects can be part of a transaction. Exceptions are objects like endpoints, which may start or stop an listenning socket.

The general rule of thumb is that if is a metadata only operation then it can be part of a transaction. If is an operation with external side effects (creates a file, opens a socket etc) then it cannot be part of a transaction because the rollback cannot be guaranteed.

The vast majority of DDL statements are metadata only, all they do is they modify some metadata catalog tables (eg. they add row in sys.tables) and as such they behave just like any other transacted operation: if the transaction is rolled back the row is removed hence the table 'disappears'. There are more details to it (eg. sys.tables is a view on top of the real internal tables like sys.objects$ and that is the real table being modified by an CREATE TABLE) but at a high level that's what's happening.


Why not just test your scenario yourself?

I just tried this - took 2 minutes.

USE [MY_DB]
GO
/****** Object:  Table [dbo].[TestTable]    Script Date: 01/25/2010 12:01:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TestTable](
    [testfield] [varchar](50) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

BEGIN TRAN

DROP TABLE TestTable 

ROLLBACK


Thread necro, it seems this no longer the case when using batching, simply run the code below, in ms sql server 2008 r2 the following IS NOT ROLLED BACK:

begin tran
go
create table AATableThatDoesNotExist
(
blah int null
)
go
create table AATableThatDoesNotExist
(
blah int null
)
go
create table AATableThatShouldNotExist
(
blah int null
)
rollback tran
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜