索引覆盖生成脚本

SET NOCOUNT ON
DECLARE @tbname VARCHAR(30)
SET @tbname = '用户档案'


DECLARE @columns TABLE ( id INT, NAME VARCHAR(30) )


INSERT @columns
SELECT ROW_NUMBER() OVER ( ORDER BY columns.object_id ) id,
columns.NAME
FROM sys.columns
JOIN sys.objects ON columns.object_id = objects.object_id
JOIN sys.types ON columns.user_type_id = types.user_type_id
WHERE columns.object_id = OBJECT_ID(@tbname)

DECLARE @CreateIndexSql VARCHAR(MAX)

DECLARE @id INT
DECLARE @name VARCHAR(MAX)
DECLARE @maxid INT
SET @id = 1
SELECT @maxid = MAX(id)
FROM @columns
WHILE ( @id <= @maxid )
BEGIN
DECLARE @include VARCHAR(MAX)= ''
SELECT @include = @include + NAME + ','
FROM @columns
SELECT @name = name
FROM @columns
WHERE id = @id
SET @include = REPLACE(',' + @include, ',' + @name + ',', ',')

SET @CreateIndexSql = ' CREATE INDEX ix_' + @tbname + '' + @name
+ ' ON ' + @tbname + '
(
' + @name + '
)
INCLUDE (,' + @include + ' )
WITH ( SORT_IN_TEMPDB = ON ) ON [PRIMARY]
'

SET @CreateIndexSql = REPLACE(@CreateIndexSql, ',,', ',')
SET @CreateIndexSql = REPLACE(@CreateIndexSql, '(,', '(')
SET @CreateIndexSql = REPLACE(@CreateIndexSql, ', )', ')')
PRINT @CreateIndexSql
EXEC ( @CreateIndexSql )
SET @id = @id + 1
END

 

 


posted @ 2012-05-13 22:27  qanholas  阅读(271)  评论(0编辑  收藏  举报