SqlServer中循环给多张表建立聚簇索引

缘由

因为在某个复(bian)杂(tai)需求中用到了170+张表进行查询,而且表中的数据过多,查起来缓慢。只能给这些表添加索引。
但是,连表名也是无法确定的(无力吐槽)。

解决方法

使用游标遍历查询出来的符合条件的表名,通过拼接sql语句进行建立索引。

代码如下:

--声明变量
declare 
    @tablename as varchar(50) = '',
    @sqlstr as varchar(max) = '';

--声明游标
declare c_tablename cursor fast_forward for (
    select name from sysobjects where xtype='u' and name like 'ear%2019' --读取库中的所有表名
);

open c_tablename;

--取第一条记录
fetch next from c_tablename into @tablename;

while @@fetch_status = 0
begin
     --组装sql语句
     set @sqlstr = 'create index ' + @tablename + '_called_duration' + ' on ' + @tablename + '(called,duration);';
     exec (@sqlstr);
     print @sqlstr;
     --取下一条记录
     fetch next from c_tablename into @tablename;
end

-- 关闭游标
close c_tablename;

-- 释放游标
deallocate c_tablename;
(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐