索引碎片SQL Server

时间:2015-01-22 00:44:17

标签: sql sql-server database indexing

我在两个表上的索引有问题。

以下是创建表格的代码:

 CREATE TABLE [dbo].[Table]
 (
    [ID] [uniqueidentifier] NOT NULL,
    [IP] [nvarchar](15) NULL,
    [Referrer] [nvarchar](1000) NULL,
    [Domain] [nvarchar](100) NULL,
    [RegID] [int] NULL,
    [Agent] [nvarchar](500) NULL,

    CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED 
    ([ID] ASC)
         WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
               ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Table] 
   ADD CONSTRAINT [DF_Table_ID]  DEFAULT (newsequentialid()) FOR [ID]
GO

和索引

CREATE NONCLUSTERED INDEX [Reg_ID] ON [dbo].[Table]
(
    [RegID] ASC
)
   WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
         SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, 
         ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

另一个索引

的表
CREATE TABLE [dbo].[Table2]
(
    [Table2_ID] [int] IDENTITY(1,1) NOT NULL,
    [TracID] [uniqueidentifier] NOT NULL,
    [F_URL] [nvarchar](1500) NULL,
    [S_URL] [nvarchar](100) NULL,
    [Time] [datetime] NULL,

    CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED  ([Table2_ID] ASC)
        WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
              IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
              ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Table2] WITH CHECK 
   ADD CONSTRAINT [FK_Table2_Table] 
     FOREIGN KEY([TracID]) REFERENCES [dbo].[Table] ([Web_Visitor_ID])
GO

ALTER TABLE [dbo].[Table2] CHECK CONSTRAINT [FK_Table2_Table]
GO

索引

CREATE NONCLUSTERED INDEX [IX_TracID] ON [dbo].[Table2]
(
    [TracID] ASC
)
     WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
           SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, 
           ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

在第一张表中,我有大约6M行和第二行8M行(每天几千行)。

我遇到问题,因为索引在4小时内碎片化达到99%。

我运行查询(sys.columns)以获取字节大小并且有结果

Table 1                    Table 2
name       bytes           name       bytes
ID          16             ID           4
IP          30             TracID       16
Referrer    2000           F_URL        3000
Domain      200            S_URL        200
RegID       4              Time         8 
Agent       1000 

有没有人有一些想法,女巫可以帮助我解决这个碎片?

1 个答案:

答案 0 :(得分:0)

您确定需要进行碎片整理吗?使用适当的硬件,碎片很少会重要。许多老派的SQL人仍然推荐它,但实际上在大多数情况下它都是过去的遗留物。

有两个原因变得无关紧要。首先,所有的读取都应该缓存在RAM中(如果没有,你需要更多的RAM - 它的价格便宜,并且会给你带来更多的好处,而不是花费在碎片整理上的努力)。其次,SSD无论如何都会消除寻道时间,因此碎片无关紧要。由于这两个变化,碎片整理所花费的时间通常都被浪费了。