简体   繁体   中英

Can update to a ParentTable cause lookup in Child table with foreign Key relationship in SQL SERVER 2008

following tables are part of Database Design. I donot have any Non-Clustered index on my Foreign Keys.

在此处输入图片说明

I am locking PatientChartImages table by using the following command

begin transaction t1
update PatientChartImages set RotationAngle = 55
--ROLLBACK TRANSACTION t1

After that, All updates to the User Table are timing out.I am attaching the SqlProfiler trace. The selected command in that image is causing TimeOut. since I am updating PatientChartImages and CreatedByUserId in PatientChartImages is not a FK to main user table, why are Fk lookups causing TimeOut.

According to Me, the following sequence is happening

  1. Transaction has a Exclusive lock on PatientChartImages
  2. Since PatientChartid in PatientChartImages is a FK to PatientChartid in PatientCharts, this is causing Foreign Key Lookup and is locking PatientCharts table.
  3. Similarly as CreatedByUserId in PatientCharts table is a FK to UserID in Users table,so FK lookups are also locking Users table.

Is my understanding on this correct? Please suggest and also tell me how can i prevent this kind of locking.

Trace ScreenShot 在此处输入图片说明

I am pretty sure your understanding of the situation is correct.

As you obviously know, when performing a SQL transaction, any update which can affect the tables you're updating needs to be prevented. Think about the ACID principles (http://en.wikipedia.org/wiki/ACID).

I think the only way round this is to use READ UNCOMMITTED or NOLOCK

Implements dirty read, or isolation level 0 locking, which means that no shared locks are issued and no exclusive locks are honored. When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels.

You can work out the risks of this for yourself.

I actually think the answer is to keep the transaction as short as possible and put up with it, as it's only doing this to protect data integrity. eg only start and end the transaction around the actual update operations.

I hope this helps a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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