1. 程式人生 > >sqlserver 生成指令碼執行建立索引

sqlserver 生成指令碼執行建立索引

 
 use MultipleAnalysisFY
 if exists(select * from sys.objects where name='execsql')
 begin
 drop table execsql;
 end
 go
 create table execsql(id int identity(1,1),sqlstr varchar(1000),flag  varchar(255));
--建立索引
insert into execsql(sqlstr,flag) 
select 'create index IX_PK_'+a.FieldName+' on '+b.TableName+'('+a.FieldName+')' ,''from ResourceConfigurationDetail a
inner join ResourceConfiguration b
on a.FID=b.ID
where a.FieldType is not null;
--建立intime 索引
insert into execsql(sqlstr,flag) 
select 'create index IX_PK_INTIME ON ' +a.tablename+'(INTIME)','' from ResourceConfiguration  a;
print('建立索引指令碼生成')
go
 use MultipleAnalysisDataFY;
 begin
 declare @sql nvarchar(2000) ,@id int
 declare cur_order cursor for  --申明遊標
  select id,sqlstr from MultipleAnalysisFY.[dbo].[execsql] where flag<>'1' order by id
  open cur_order --開啟遊標
  fetch next from   cur_order into @id,@sql
  RAISERROR ('執行開始......', 10, 1) WITH NOWAIT
  while @@FETCH_STATUS=0
  begin
   declare @info varchar(255)
   set @info= @sql+'正在執行,本次id為'+convert(varchar(10),@id)+'當前時間:'+convert(varchar(100),getdate(),120);
   RAISERROR (@info, 10, 1) WITH NOWAIT
   begin try  
   EXEC sp_executesql @sql;--執行指令碼
   declare @info1 varchar(255)
   set @info1= @sql+'執行完成,當前時間:'+convert(varchar(100),getdate(),120);
   update MultipleAnalysisFY.[dbo].[execsql]  set flag='1' where 
[email protected]
RAISERROR (@info1, 10, 1) WITH NOWAIT end try begin catch declare @error varchar(255) set @error='執行錯誤,錯誤資訊id:'+convert(varchar(10),@id)+',錯誤資訊:'+ERROR_MESSAGE(); RAISERROR (@error, 11, 1) WITH NOWAIT end catch fetch next from cur_order into @id,@sql end close cur_order --關閉遊標 DEALLOCATE cur_order--釋放遊標 print('任務處理完成') end