数据库查询优化——给临时表建索引
2017-09-14 14:45 若藜520 阅读(8183) 评论(0) 编辑 收藏 举报平时查询数据库时为了查询更加快速,一般都会用到临时表,如select * into #t from tableA ,但是如果数据过大,但但用临时可能也很慢,这时候可以给临时表建个索引,如CREATE INDEX IX_TempTable ON #T(字段1,字段2,字段3)。如果临时表字段未知的时候怎么建立索引呢,可以用以下sql把临时表的所有字段查出来,给所有字段建立索引
DECLARE @COL VARCHAR(1000)
SET @COL = ''
SELECT @COL = @COL + COLUMN_NAME + ',' FROM
TEMPDB.INFORMATION_SCHEMA.COLUMNS A
INNER JOIN(SELECT [NAME] FROM TEMPDB.dbo.sysobjects WHERE [ID] = OBJECT_ID(N'TEMPDB..#T'))B
ON A.TABLE_NAME = B.[NAME] AND A.ORDINAL_POSITION <= 3
ORDER BY ORDINAL_POSITION
print @COL
SET @COL = LEFT(@COL, LEN(@COL) - 1)
EXEC('CREATE INDEX IX_TempTable ON #T(' + @COL + ')')