Clustered index on temp table

痴心易碎 提交于 2019-12-22 08:47:28

问题


I'm trying to optimize a procedure that has code like the following:

CREATE TABLE #t1 (c1 int, c2 varchar(20), c3(varchar(50)...)

CREATE CLUSTERED INDEX ix_t1 ON #t1(c3) ON [PRIMARY]

I wanted to improve that by moving the CLUSTERED index into the table declaration (more caching friendly), but c3 is not unique so this doesn't work:

CREATE TABLE #t1 (c1 int, c2 varchar(20), c3 varchar(50)..., UNIQUE CLUSTERED (c3))

Is there a way to declare a clustered that is not unique in the temp table declaration?


回答1:


No there is not...the existence of the ability to define clustered as an option in table creation is to support declaring primary key and unique column constraints, which themselves create indexes. In other words, CLUSTERED in the CREATE TABLE statement is specifying whether or not the index created by the UNIQUE constraint should be clustered or nonclustered, which is important because a table can only have one clustered index.




回答2:


Yes, it is possible in SQL Server 2014 and above, Create table on MSDN. From 2014 you can specify the indexes inline with the create table statement.

 if object_id('tempdb..#t1') is not null drop table #t1;

CREATE TABLE #t1 (
    c1 int, 
    c2 varchar(20), 
    c3 varchar(50), 

    index [CIX_c3] CLUSTERED (c3),
    index [IX_c1] nonclustered (c1)
)

insert #t1(c3) values ('a'), ('a'), ('a')

select * from #t1



回答3:


This can be done by adding an identity column, such as:

CREATE TABLE #t1 (rowID int not null identity(1,1),
                     c1 int, c2 varchar(20), c3 varchar(50),
                     UNIQUE CLUSTERED (c3,rowID)
                 )

Including the rowID in the index will insure that it is unique, even if c3 is not.

You verify the index created with:

EXEC tempdb.dbo.sp_helpindex '#t1'


来源:https://stackoverflow.com/questions/7663967/clustered-index-on-temp-table

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