-
Notifications
You must be signed in to change notification settings - Fork 1
/
indexCursor.sql
131 lines (90 loc) · 2.23 KB
/
indexCursor.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/*
drop table IndexInfo
create table IndexInfo(
pk int identity(1,1),
TableName sysname null,
IndexName sysname null,
IndexID int null,
IndexType sysname null,
IndexSql nvarchar(4000) null,
sourceFG sysname null,
destFG sysname null,
IndexStatus int default 0, 0-pending 1-in progress 2-done 3-dropped
constraint pk_indexinfo primary key clustered (pk)
)
*/
--1 drop all NCI's
declare @TableName sysname
declare @IndexName sysname
declare @sql nvarchar(4000)
declare @pk int
declare cur cursor for
select TableName, IndexName, pk from SueDB.dbo.IndexInfo
where IndexID > 1
--and IndexStatus <> 3 --3=dropped
open cur
fetch next from cur
into @TableName, @IndexName, @pk
while (@@FETCH_STATUS=0) begin
set @sql = 'IF (EXISTS(SELECT * FROM sys.indexes WHERE object_id = object_id(''dbo.'+@TableName+''') AND NAME ='''+@indexname+'''))
DROP INDEX ['+@tablename+'].['+@IndexName+']'
--set @sql = 'DROP INDEX ['+@tablename+'].['+@IndexName+']'
print @sql
exec sp_executesql @sql
update suedb.dbo.indexinfo
set indexStatus = 3
where pk=@pk
fetch next from cur
into @tableName, @indexName, @pk
end
close cur
deallocate cur
--2 move CI's
declare cur cursor for
select tableName, indexName, indexSQL, pk
from sueDB.dbo.indexinfo
where indexID = 1
and indexStatus <> 2
open cur
fetch next from cur into
@tableName, @indexName, @sql, @pk
while(@@FETCH_STATUS = 0)
begin
update sueDB.dbo.IndexInfo
set IndexStatus = 1 --in progress
where pk = @pk
print @sql
print @pk
exec sp_executesql @sql
update sueDB.dbo.IndexInfo
set IndexStatus = 2 --done
where pk = @pk
print '----'
fetch next from cur into @tablename, @indexname, @sql, @pk
end
close cur
deallocate cur
--3 create NCIs
declare cur cursor for
select TableName, IndexName, IndexSQL, pk from SueDB.dbo.IndexInfo
where IndexID > 1
and IndexStatus <> 2
open cur
fetch next from cur
into @TableName, @IndexName, @sql, @pk
while (@@FETCH_STATUS=0) begin
update sueDB.dbo.IndexInfo
set IndexStatus = 1 --in progress
where pk = @pk
print @sql
print @pk
exec sp_executesql @sql
update sueDB.dbo.IndexInfo
set IndexStatus = 2 --done
where pk = @pk
print '----'
fetch next from cur
into @tableName, @indexName, @sql, @pk
end
close cur
deallocate cur