Dynamically name indexes in SQL Server 2005?

*爱你&永不变心* 提交于 2020-01-11 04:55:20

问题


As most people who work with Sql Server know, you can declare a temporary table like so:

create table #foo 
    (
    row_id int identity not null primary key,
    bar varchar(50) not null default 'YoMomma'
    );

...this will create a primary key and a default constraint on this temporary table; the names for these objects will be unique, dynamically created by Sql Server.

Is it possible to create a dynamically named index for the table after it's been created? I have a case where a stored procedure using temporary tables may be running multiple instances at the same time, and I'd like to increase the performance without risking a conflict between identically named objects in the tempdb database. CREATE INDEX command requires an explicit index name.

I am looking for a solution that does not involve dynamic SQL, just dynamic names.


回答1:


This is a non issue. Index names only have to be unique within a table scope, not globally across table scopes. Only constraint names have to be unique within an entire database schema.

So, for example, you can run this in multiple concurrent connections with no problems

CREATE TABLE #T
(
C INT
)

CREATE UNIQUE CLUSTERED INDEX ix on #T(C)

But this would fail under concurrency

ALTER TABLE #T
ADD CONSTRAINT UQ UNIQUE NONCLUSTERED (C)



回答2:


Should be able to do:

CREATE INDEX #foo1 ON #foo(bar);


来源:https://stackoverflow.com/questions/8422379/dynamically-name-indexes-in-sql-server-2005

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