从长远来看,删除或“停用”行,或者在什么情况下,它会更好吗?
我注意到从表中删除了大量行后产生的开销。为什么会发生这种情况以及可以做些什么1)防止它和2)修复它?
答案 0 :(得分:3)
如果要删除大量/旧的或存档的历史记录 - 直接删除它们。
在短期内,对于手动用户级删除,通常首选“软删除”。手动删除可能不会超过约10%的记录,因此指数有效性仍然很高。
“软删除”还具有管理员可以取消删除错误删除和参照完整性的主要好处。所引用的交易细节都很愉快!
对于长期归档/删除,您希望从索引中删除这些记录 - 除了专有&特定于数据库的“条件索引”,我倾向于避免,从表中删除它们是从索引中删除它们的唯一方法。
答案 1 :(得分:2)
对于SQL Server ...
我认为重要的是要知道,如果您要删除非常大的表(意味着大量记录)的所有记录,您将首先要截断,然后删除索引。它效率更高。
如果要删除记录的子集,并且已应用索引,请使用DELETE FROM {table} WHERE {condition}语法。如果这样做,则必须首先按依赖关系层次结构的顺序从依赖表中删除。基本上与插入记录的方式完全相反,首先从非依赖表开始。
使用表依赖关系层次结构删除记录:
Dependent / Child Table(取决于Dependency表):
DELETE FROM [table_dependent]; -- "dependent" is a relative term since this may be part of a hierarchy; a FK in this table points to the PK of the [table_independent] table; in a physical database model, this table is sometimes referred to as the child table
依赖/父表:
DELETE FROM [table_independent]; -- "independent" is a relative term since this may be part of a hierarchy; the PK of this table has a FK in a [table_dependent] table; in a physical database model, this is sometimes referred to as the parent table.
注意:
如果存在层次结构,则记录来自"最深的"应首先删除从属表。这意味着必须首先删除此表的索引。然后,您应该处理层次结构,直到到达父表。
使用表依赖关系层次结构INSERT记录:
SET IDENTITY_INSERT [table_independent] ON
INSERT INTO [table_independent]
(
[column that is not identity column],
[column that is not identity column],
[column that is not identity column]
)
VALUES
(
'1',
'2',
'3'
);
SET IDENTITY_INSERT [table_independent] OFF
SET IDENTITY_INSERT [table_dependent] ON
INSERT INTO [table_dependent]
(
[column that is not identity column],
[column that is not identity column],
[table_independent fk column]
)
VALUES
(
'1',
'2',
'3'
);
SET IDENTITY_INSERT [table_dependent] OFF