HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

Why is it not possible to create indexes on temp tables in SNAPSHOT isolation?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
whytablesisolationcreatetempindexessnapshotpossiblenot

Problem

When I try to create indexes on a temporary table in SQL Server when using the SNAPSHOT transaction isolation, I get this error:


Transaction failed because this DDL statement is not allowed inside a snapshot isolation transaction. Since metadata is not versioned, a metadata change can lead to inconsistency if mixed within snapshot isolation.

Why is it not allowed to create indexes on temporary tables in SQL Server when using snapshots?

I don't understand this, if I'm allowed to create temporary tables, why am I not allowed to add indexes to them?

Solution

In modern versions of SQL Server (2014+) you can create the indexes when you create the table, e.g.:

create table #t(id int primary key, a int, index ix_a nonclustered(a))


Also you can create the temp table before the snapshot transaction starts.

Almost all DDL is prohibited within a SNAPSHOT transaction. ALTER TABLE and TRUNCATE TABLE are obviously not allowable. CREATE TABLE is whitelisted. CREATE INDEX could be whitelisted, but simply isn't.

Code Snippets

create table #t(id int primary key, a int, index ix_a nonclustered(a))

Context

StackExchange Database Administrators Q#206804, answer score: 11

Revisions (0)

No revisions yet.