简体   繁体   English

在SQL Server和DB锁中使用外键

[英]Using foreign key in SQL server and DB locks

I have been working with SQL Server for a long time I always use FKs and indexes when a logic connection between tables exist 我已经使用SQL Server很长时间了,当表之间存在逻辑连接时,我总是使用FK和索引

Example: 例:

MyTable1
{
    ID      BIGINT IDENTITY (1, 1)  NOT NULL,
    SomeData    NVARCHAR(255)       NOT NULL,
    MyFK        BIGINT          NULL -- this is a FK to MyTable2.ID
}

MyTable2
{
    ID      BIGINT IDENTITY (1, 1)  NOT NULL,
    SomeData    NVARCHAR(255)       NOT NULL
}

Now to the problem, When I execute some bulk update operations on MyTable1 that update MyFK, and in the same time execute an insert statements to MyTable2, we hang till a timeout occur or the update is done and the locks are released. 现在要解决的问题是,当我在MyTable1上执行一些批量更新操作以更新MyFK,同时对MyTable2执行插入语句时,我们会一直挂起,直到发生超时或更新完成并释放了锁。

As far as I know when inserting to a table that has FKs, the DB engine needs to get a lock on the relevant table to validate the FK, and that is the source for the problem. 据我所知,当插入具有FK的表时,数据库引擎需要获得相关表的锁以验证FK,这就是问题的根源。

Things I tries to resolve the problem: 我尝试解决的问题:

Both solutions lead me to deadlocks and bad performance. 两种解决方案都导致我陷入僵局和性能不佳。

When I removed the FK, it all worked well, but there is the risk of data corruption. 当我卸下FK时,一切正常,但存在数据损坏的风险。

Questions: 问题:

  1. Is there any recommended set of rules on where to use a FK and where not to? 对于在哪里使用FK和在哪里不使用FK,是否有任何建议的规则集?
  2. Can you offer me any other solution but removing the FK to overcome my problem? 除了移除FK可以解决我的问题之外,您能否提供其他解决方案?

Just in case the page asasfrob found goes down, the answer it gave was: 万一asasfrob找到的页面出现故障,它给出的答案是:

Define the primary key on the parent table (TableA) as a non-clustered index. 将父表(TableA)上的主键定义为非聚集索引。 Once you do that, the issue won't occur since the look-up will occur against the non-clustered index and that won't be in a locked state since the PK column is not being modified. 一旦执行此操作,就不会出现此问题,因为将针对非聚集索引进行查找,并且由于未修改PK列,因此不会处于锁定状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM