从具有约束的表中删除记录

时间:2015-01-22 09:48:02

标签: sql sql-server sql-server-2008 tsql

我有两个表(PreOrder,PreOrderDetails),我想从中删除记录。这些表具有经典关系,其中详细信息表的外键引用预订表中的主键。 PreOrder拥有约1600万条记录,详细信息约为6000万条。

CREATE TABLE [dbo].[PreOrder](
    [PreOrderId] [uniqueidentifier] NOT NULL,
    -- more columns
 CONSTRAINT [PK_PreOrder] PRIMARY KEY NONCLUSTERED 
(
    [PreOrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[PreOrder]  WITH CHECK ADD  CONSTRAINT [FK_PreOrder_PreOrder] FOREIGN KEY([PreOrderId])
REFERENCES [dbo].[PreOrder] ([PreOrderId])
GO

ALTER TABLE [dbo].[PreOrder] CHECK CONSTRAINT [FK_PreOrder_PreOrder]


CREATE TABLE [dbo].[PreOrderDetail](
    [PreOrderDetailId] [uniqueidentifier] NOT NULL,
    [PreOrderId] [uniqueidentifier] NOT NULL,
    more columns
 CONSTRAINT [PK_PreOrderDetail] PRIMARY KEY CLUSTERED 
(
    [PreOrderDetailId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[PreOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_PreOrderDetail_PreOrder] FOREIGN KEY([PreOrderId])
REFERENCES [dbo].[PreOrder] ([PreOrderId])
GO

ALTER TABLE [dbo].[PreOrderDetail] CHECK CONSTRAINT [FK_PreOrderDetail_PreOrder]
GO

从预订中删除5条记录需要90秒,这太慢了。我猜它是因为约束,每次要删除一个preorderid时,都要检查完整的preorderdetails表。 这个假设是否正确?

我可以做些什么来加快速度?现在记录的插入速度比删除它们的速度快。

1 个答案:

答案 0 :(得分:0)

是[PreOrderDetail]上没有索引。[PreOrderId]对插入很有用。
但基于列的选择和删除不会有好处 您需要[PreOrderDetail]上的索引。[PreOrderId]

使用uniqueidentifier进行PK或索引效率不高,会迅速崩溃。