Skip to content

Commit 951039d

Browse files
committed
Add scritps da pasta Index
1 parent 47a1eec commit 951039d

20 files changed

+2693
-0
lines changed

Index/ColunasPosicaoIndex.sql

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*#info
2+
3+
# Autor
4+
Rodrigo Ribeiro Gomes
5+
6+
# Detalhes
7+
Retorna a lista de tabelas e colunas e os índices cujo essa coluna estão em uma posição específica do indice.
8+
Por exemplo, com o valor padrão do filtro key_ordinal, ele retorna apenas os índices em que a coluna é a primeira posição no índice.
9+
10+
Note que a função STRING_AGG só existe no 2019 em diante.
11+
Se você precisar executar em uma versão anterior, pode usar outras técnicas, com FOR XML, por exemplo.
12+
13+
*/
14+
SELECT
15+
t.name
16+
,c.name
17+
,I.Indexes
18+
FROM
19+
sys.tables t
20+
join
21+
sys.columns c
22+
on c.object_id = t.object_id
23+
OUTER APPLY (
24+
SELECT
25+
Indexes = STRING_AGG(i.name,',')
26+
FROM
27+
sys.index_columns IC
28+
join
29+
sys.indexes i
30+
on i.object_id = ic.object_id
31+
and i.index_id = ic.index_id
32+
WHERE
33+
IC.object_id = C.object_id
34+
and
35+
IC.key_ordinal = 1
36+
AND
37+
IC.object_id = C.object_id
38+
AND
39+
IC.column_id = C.column_id
40+
) I
41+
42+
43+

Index/Compression.sql

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
/*#info
2+
3+
# Autor
4+
Rodrigo Ribeiro Gomes
5+
6+
# Detalhes
7+
Comprime todos os índices do banco atual (usando PAGE).
8+
9+
10+
*/
11+
DECLARE
12+
@Execute bit = 0; --> Troque para 1 para rodar! 0 faz apenas printar os comandos
13+
14+
15+
IF OBJECT_ID('tempdb..#AllIndexes') IS NOT NULL
16+
DROP TABLE #AllIndexes;
17+
18+
CREATE TABLE #AllIndexes (
19+
RowId int not null identity
20+
,TableName nvarchar(1000)
21+
,IndexName nvarchar(1000)
22+
,IndexFillFactor int
23+
,AllowOnline bit
24+
,AlterType AS CASE WHEN IndexName IS NULL THEN 'TABLE' ELSE 'INDEX' END PERSISTED
25+
,AlterObject AS CASE WHEN IndexName IS NULL THEN TableName ELSE QUOTENAME(IndexName)+' ON '+TableName END PERSISTED
26+
,AlterOnline AS CASE WHEN AllowOnline = 1 THEN 'ON' ELSE 'OFF' END PERSISTED
27+
,AlterFF AS CASE WHEN IndexFillFactor BETWEEN 1 AND 90 THEN '90' ELSE NULL END PERSISTED
28+
)
29+
30+
INSERT INTO
31+
#AllIndexes(
32+
TableName
33+
,IndexName
34+
,IndexFillFactor
35+
,AllowOnline
36+
)
37+
SELECT
38+
QUOTENAME(OBJECT_SCHEMA_NAME(I.object_id))+'.'+QUOTENAME(OBJECT_NAME(I.object_id))
39+
,I.name
40+
,I.fill_factor
41+
,O.CanOnline
42+
FROM
43+
sys.indexes I
44+
INNER JOIN
45+
sys.tables T
46+
ON T.object_id = I.object_id
47+
CROSS APPLY
48+
(
49+
SELECT
50+
CanOnline = MIN
51+
(
52+
CASE
53+
WHEN ISNULL(IC.index_id,1) = 1 AND T.name IN ('image','ntext','text') THEN 0
54+
WHEN IC.index_id > 1 AND T.name IN ('image','ntext','text') AND IC.is_included_column = 0 THEN 0
55+
WHEN IC.index_id > 1 AND T.name IN ('image','ntext','text') AND IC.is_included_column = 0 THEN 0
56+
ELSE 1
57+
END
58+
)
59+
--,c.name ColName
60+
--,T.name IndexName
61+
--,IC.is_included_column
62+
FROM
63+
sys.columns C
64+
INNER JOIN
65+
sys.types T
66+
ON T.user_type_id = C.user_type_id
67+
LEFT JOIN
68+
sys.index_columns IC
69+
ON C.object_id = IC.object_id
70+
AND C.column_id = IC.column_id
71+
AND IC.index_id = I.index_id
72+
WHERE
73+
C.object_id = I.object_id
74+
AND
75+
( (IC.index_id IS NULL AND I.index_id <= 1)
76+
OR
77+
(IC.index_id IS NOT NULL AND I.index_id > 0)
78+
)
79+
) O
80+
WHERE
81+
I.is_disabled = 0
82+
AND
83+
I.type <= 2
84+
AND
85+
NOT EXISTS (
86+
SELECT * FROM sys.partitions P
87+
WHERE P.object_id = I.object_id AND P.index_id = I.index_id
88+
AND P.data_compression_desc= 'PAGE'
89+
)
90+
91+
92+
-- loop
93+
DECLARE @NextRow int
94+
,@SQL_Compress nvarchar(max)
95+
,@TotalRows int
96+
;
97+
SET @NextRow = 1;
98+
SET @TotalRows = (SELECT MAX(RowId) FROM #AllIndexes)
99+
100+
101+
WHILE 1 = 1
102+
BEGIN
103+
104+
-- aqui é o comando de alter que será usado!
105+
SELECT TOP 1
106+
@SQL_Compress = 'ALTER '+AI.AlterType+' '+AI.AlterObject+' REBUILD WITH (DATA_COMPRESSION = PAGE, ONLINE = '+AlterOnline+ISNULL(', FILLFACTOR = '+AlterFF,'')+')'
107+
FROM
108+
#AllIndexes AI
109+
WHERE
110+
AI.RowId = @NextRow
111+
112+
IF @@ROWCOUNT = 0
113+
BREAK;
114+
115+
set @NextRow = @NextRow + 1;
116+
117+
RAISERROR('Compressing %d/%d',0,1,@NextRow,@TotalRows) WITH NOWAIT;
118+
RAISERROR(' SQL: %s',0,1,@SQL_Compress) WITH NOWAIT;
119+
if @Execute = 1
120+
exec sp_Executesql @SQL_Compress;
121+
122+
123+
124+
END
125+
126+
127+
128+
129+
130+
131+
132+
133+
134+
135+
136+
137+
138+
139+
140+
141+
142+
143+
144+

Index/EstimateIndexCreation.sql

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/*#info
2+
3+
# Autor
4+
Rodrigo Ribeiro Gomes
5+
6+
# Detalhes
7+
Esse script foi uma tentativa de estimar o tempo necessário para criar um índice.
8+
Me lembro de ter usado algumas vezes em produção e ter resultados muitos próximos do real.
9+
A ideia é muito simples:
10+
- Dado uma tabela (@TableName) e uma lista de colunas (@TestCols) que quero indexar
11+
- Crio uma cópia dessa tabela com uma amostra de linhas (parâmetro @TestSize)
12+
- Então, crio o índice na cópia, com as colunas desejada e mensuro o tempo que levou.
13+
- No final, faço uma regra de três simples para estimar para o total de linhas da tabela.
14+
15+
16+
17+
18+
*/
19+
20+
DECLARE
21+
@TableName sysname
22+
,@TestSize bigint = 50000
23+
,@TestCols nvarchar(max) = NULL
24+
25+
SET @TableName = 'Posts'
26+
set @TestCols = 'Id'
27+
28+
----
29+
set nocount on;
30+
31+
IF OBJECT_ID(@TableName) IS NULL
32+
BEGIN
33+
RAISERROR('Invalid table %s',16,1,@TableName);
34+
RETURN;
35+
END
36+
37+
if @TestCols is null
38+
BEGIN
39+
RAISERROR('Invalid cols',16,1);
40+
RETURN;
41+
END
42+
43+
DECLARE
44+
@CopyTableName sysname
45+
,@sql nvarchar(MAX)
46+
,@TotalSize bigint = 0
47+
,@StartTime datetime
48+
,@EndTime datetime
49+
,@TotalCreateTime bigint
50+
,@TableSize bigint
51+
52+
SET @CopyTableName = 'zzzIndexCreationEstimate_'+replace(@TableName,'.','_')
53+
54+
SET @sql = 'SELECT '+@TestCols+' INTO '+@CopyTableName+' FROM '+@TableName+' WHERE 1 = 2' +
55+
'UNION ALL SELECT '+@TestCols+' FROM '+@TableName+' WHERE 1 = 2'
56+
exec(@sql)
57+
58+
IF @@ERROR !=0
59+
RETURN;
60+
61+
62+
RAISERROR('Test table %s created! To drop run: DROP TABLE %s',0,1,@CopyTableName,@CopyTableName) with nowait;
63+
64+
SET @sql = 'INSERT INTO '+@CopyTableName+' SELECT '+@TestCols+' FROM '+@TableName+' TABLESAMPLE(10000 ROWS)'
65+
exec(@sql)
66+
67+
raiserror('Loading copy Table...',0,1) with nowait;
68+
while @TotalSize < @TestSize
69+
begin
70+
71+
SELECT @TotalSize = sum(rows) FROM sys.partitions p where p.object_id = object_id(@CopyTableName)
72+
exec(@sql)
73+
end
74+
75+
set @sql = 'create index ixTest on '+@CopyTableName+'('+@TestCols+')';
76+
raiserror('Creating test index on %s',0,1,@CopyTableName)
77+
set @StartTime = getdate();
78+
exec(@sql);
79+
set @EndTime = getdate();
80+
select @StartTime,@EndTime
81+
set @TotalCreateTime = ISNULL(NULLIF(datediff(ms,@StartTime,@EndTime),0),1)
82+
83+
84+
85+
SELECT @TableSize = sum(rows) FROM sys.partitions p where p.object_id = object_id(@TableName)
86+
and p.index_id <= 1
87+
88+
select CopyTotalRows = @TotalSize
89+
,CopyCreationDurationMs = @TotalCreateTime
90+
,RealTotalRows = @TableSize
91+
,RealCreationEstimationMs = (@TotalCreateTime*@TableSize)/@TotalSize
92+
93+
94+
95+
select DropThisTableToEnd = 'drop table '+@CopyTableName;
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*#info
2+
3+
# Autor
4+
Rodrigo Ribeiro Gomes
5+
6+
# Detalhes
7+
Traz informacoes sobre o progresso do population de um fulltext index em uma tabela especifica.
8+
9+
10+
*/
11+
12+
DECLARE
13+
@TableId int = OBJECT_ID('NomeTabela')
14+
15+
SELECT
16+
T.object_id
17+
,name
18+
,R.TotalRows
19+
,IndexedRows = OBJECTPROPERTYEX(T.object_id,'TableFulltextItemCount')
20+
,PendingChanges = OBJECTPROPERTYEX(T.object_id,'TableFullTextPendingChanges')
21+
,FailCount = OBJECTPROPERTYEX(T.object_id,'TableFulltextFailCount')
22+
,TotalProcessed = OBJECTPROPERTYEX(T.object_id,'TableFulltextDocsProcessed')
23+
,PopStatus = OBJECTPROPERTYEX(T.object_id,'TableFulltextPopulateStatus')
24+
,Progress = CONVERT(bigint,OBJECTPROPERTYEX(T.object_id,'TableFulltextItemCount'))*100/R.TotalRows
25+
,PopType = FP.population_type_description
26+
,FP.range_count
27+
,FP.completed_range_count
28+
,FP.outstanding_batch_count
29+
,FP.status_description
30+
,FI.incremental_timestamp
31+
,FI.crawl_type_desc
32+
,FI.crawl_start_date
33+
,FI.crawl_end_date
34+
,FI.data_space_id
35+
,FI.change_tracking_state_desc
36+
from
37+
sys.tables t
38+
cross apply
39+
(
40+
select TotalRows = sum(rows) from sys.partitions p
41+
where p.object_id = t.object_id
42+
and p.index_id <= 1
43+
) R
44+
left join
45+
sys.dm_fts_index_population FP
46+
ON FP.table_id = T.object_id
47+
left join
48+
sys.fulltext_indexes FI
49+
ON FI.object_id = T.object_id
50+
where
51+
t.object_id = @TableId
52+
53+
select * from sys.dm_fts_outstanding_batches where table_id = @TableId
54+
select * from sys.dm_fts_population_ranges
55+
select * from sys.fulltext_index_fragments where table_id = @TableId
56+
57+
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*#info
2+
3+
# Autor
4+
Rodrigo Ribeiro Gomes
5+
6+
# Detalhes
7+
Traz informacoes sobre todos os indexes fulltext e processos de population ativo (todas do banco atual)
8+
9+
10+
*/
11+
12+
select
13+
c.name as Nome
14+
,c.path as Cam
15+
,c.is_default as Padrao
16+
,fac.memory_address as AddrM
17+
,fac.name as ftcNome
18+
,fac.status as St
19+
,fac.previous_status as prSt
20+
,fac.is_paused as Paused
21+
,fac.status_description as StDesc
22+
,fac.active_fts_index_count as idxAt
23+
,fac.auto_population_count as ppAuto
24+
,fac.manual_population_count as ppM
25+
,fac.full_incremental_population_count as ppINC
26+
,fac.row_count_in_thousands as RowCnt
27+
,object_name(fip.table_id) as Tab
28+
,fip.memory_address as fipAddr
29+
,fip.population_type_description as popDesc
30+
,fip.is_clustered_index_scan as ClusterSc
31+
,fip.range_count
32+
,fip.completed_range_count as RangCntC
33+
,fip.outstanding_batch_count as OBC
34+
,fip.status
35+
,fip.status_description
36+
,fip.completion_type
37+
,fip.completion_type_description
38+
,fip.worker_count
39+
,fip.start_time
40+
,fip.incremental_timestamp
41+
from
42+
sys.fulltext_catalogs c
43+
left join
44+
sys.dm_fts_active_catalogs fac on fac.catalog_id = c.fulltext_catalog_id
45+
and fac.database_id = db_id()
46+
left join
47+
sys.dm_fts_index_population fip ON fip.catalog_id = c.fulltext_catalog_id
48+
and fip.database_id = db_id()

0 commit comments

Comments
 (0)