积极答复者
可否一次给多个表加索引

问题
答案
-
CREATE TABLE t1(a int) CREATE TABLE t2(a INT) CREATE TABLE t3(a int) GO DECLARE @s VARCHAR(8000) SELECT @s=isnull(@s+CHAR(10)+CHAR(13),'')+'create index index_'+tbName+'_a on '+tbName+'(a)' FROM (SELECT 't1' AS tbName UNION ALL SELECT 't2' UNION ALL SELECT 't3')k PRINT @s /* create index index_t1_a on t1(a) create index index_t2_a on t2(a) create index index_t3_a on t3(a)*/ --执行 EXEC (@s)
- 已标记为答案 Vincent-Z 2010年8月9日 15:16
全部回复
-
CREATE TABLE t1(a int) CREATE TABLE t2(a INT) CREATE TABLE t3(a int) GO DECLARE @s VARCHAR(8000) SELECT @s=isnull(@s+CHAR(10)+CHAR(13),'')+'create index index_'+tbName+'_a on '+tbName+'(a)' FROM (SELECT 't1' AS tbName UNION ALL SELECT 't2' UNION ALL SELECT 't3')k PRINT @s /* create index index_t1_a on t1(a) create index index_t2_a on t2(a) create index index_t3_a on t3(a)*/ --执行 EXEC (@s)
- 已标记为答案 Vincent-Z 2010年8月9日 15:16
-
基本逻辑:
1、用一个表(也可以是临时表)存储你的表名,假如是A表,只有一个字段即为表名(也可以为两个字段,一个为表名,一个为需要在上面创建索引的字段名)
2、循环:
{
从A表中每次取一个字符串存到变量,然后从表中删除它。
构建一个创建索引的SQL语句
执行SQL语句
}
直到A表为空
declare @sql varchar(1000)
declare @tbl_name varchar(50)
declare @tbl_cnt int
--这里请根据实际情况构建自己的表
select name
into #tmp_tbl
from sys.tables
set @tbl_cnt = @@rowcount
while @tbl_cnt > 0
begin
set @tbl_name = ( select top 1 name from #tmp_tbl )
delete from #tmp_tbl
where name = @tbl_name
set @tbl_cnt = @tbl_cnt - 1
--"columnname"为索引字段
set @sql = 'create index index_' + @tbl_name + '_"columnname" on ' + @tbl_name + '("columnname")'
exec (@sql)
end
上面代码没有经过编译验证,逻辑基本就是这样了。