Are schema modifying commands transactional?

泄露秘密 提交于 2019-12-24 06:23:14

问题


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 the table will have more then a few tens of rows.


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/2133781/are-schema-modifying-commands-transactional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!