前的项目是做数据库的归档,在每次archive后都需要对原数据库的索引进行rebuild,以减少索引碎片,于是乎就自己写了一段sql:
DECLARE @tablename VARCHAR(50)
DECLARE @indexname VARCHAR(50)DECLARE @cmdsql NVARCHAR(MAX)DECLARE index_cursor CURSORFOR SELECT OBJECT_NAME(object_id) AS Table_Name , nameFROM sys.indexesWHERE name IS NOT NULL AND OBJECT_NAME(object_id) IN ( SELECT name FROM sys.tables ) OPEN index_cursorFETCH NEXT FROM index_cursorINTO @tablename,@indexnameWHILE @@FETCH_STATUS = 0
BEGIN SET @cmdsql ='ALTER INDEX ['+@indexname+'] ON [dbo].['+@tablename+'] REBUILD WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, SORT_IN_TEMPDB = OFF, ONLINE = OFF )' EXECUTE sp_executesql @cmdsql PRINT @cmdsql FETCH NEXT FROM index_cursor INTO @tablename,@indexname ENDCLOSE index_cursorDEALLOCATE index_cursor希望对大家有帮助!