Create a test fragmented index

The following script allows you to quickly create a fragmented index for testing:

USE tempdb;
-- drop test table if exists
IF (OBJECT_ID(N'akawn_t',N'U') IS NOT NULL)
BEGIN 
DROP TABLE akawn_t;
END
--create table
CREATE TABLE akawn_t (c1 float PRIMARY KEY, c2 nchar(1000));
GO
--insert 100 records
INSERT INTO akawn_t 
SELECT RAND(), '1';
GO 100
-- delete some records
DELETE FROM akawn_t
WHERE CAST((c1 * 100) AS smallint) % 2  = 1;
GO
-- view fragmentation
SELECT
'[' + OBJECT_SCHEMA_NAME(a.[object_id]) + '].[' + OBJECT_NAME(a.[object_id]) + ']' AS table_name
,b.[name] AS index_name
,a.avg_fragmentation_in_percent
,a.index_type_desc
,a.*
,b.*
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, NULL) a, sys.indexes b
WHERE 1=1
AND a.[object_id] = b.[object_id]
AND a.index_id = b.index_id
AND a.avg_fragmentation_in_percent > 1;

image1

Leave a Reply