MSSQL Reindex All Table in Database

declare @name varchar(128), –ประกาศตัวแปรสำหรับเก็บชื่อ ตาราง
@user varchar(128), –ประกาศตัวแปรสำหรับเก็บชื่อ เจ้าของตาราง
@statement varchar(1000)

declare tablename cursor for –ประกาศตัวแปร cursor ข้อมูล ตาราง จาก sysobjects
select o.name, u.name
from sysobjects as o, sysusers as u
where o.uid = u.uid
and xtype = ‘U’

open tablename –เปิด cursor

fetch next from tablename –อ่านข้อมูลจาก cursor และให้ข้อมูลเข้าตัวแปร
into @name, @user

while @@fetch_status = 0 — วนลูป cursor จนกว่าหมดข้อมูล
begin
set @statement = ‘DBCC DBREINDEX (”[‘ + @user + ‘].[‘ + @name + ‘]”)’ –สร้าง sql statement เพื่อ re-index ตาราง
print @statement + ‘…’
execute (@statement) — สั่งให้ execute sql statement ที่ re-index ตาราง
fetch next from tablename
into @name, @user
end

close tablename — ปิด cursor
deallocate tablename — เคลียร์ memory

Leave a Reply

Your email address will not be published. Required fields are marked *