Nature of Lock is child table while deletion(sql server)

Posted by Mubashar Ahmad on Stack Overflow See other posts from Stack Overflow or by Mubashar Ahmad
Published on 2010-04-04T06:41:24Z Indexed on 2010/04/04 6:53 UTC
Read the original article Hit count: 524

Dear Devs

From couple of days i am thinking of a following scenario

Consider I have 2 tables with parent child relationship of kind one-to-many. On removal of parent row i have to delete the rows in child those are related to parents. simple right?

i have to make a transaction scope to do above operation i can do this as following; (its psuedo code but i am doing this in c# code using odbc connection and database is sql server)

  1. begin transaction(read committed)
  2. Read all child where child.fk = p1
  3. foreach(child) delete child where child.pk = cx
  4. delete parent where parent.pk = p1
  5. commit trans

OR

  1. begin transaction(read committed)
  2. delete all child where child.fk = p1
  3. delete parent where parent.pk = p1
  4. commit trans

Now there are couple of questions in my mind

  1. Which one of above is better to use specially considering a scenario of real time system where thousands of other operations(select/update/delete/insert) are being performed within a span of seconds.

  2. does it ensure that no new child with child.fk = p1 will be added until transaction completes?

  3. If yes for 2nd question then how it ensures? do it take the table level locks or what.

  4. Is there any kind of Index locking supported by sql server if yes what it does and how it can be used.

Regards Mubashar

© Stack Overflow or respective owner

Related posts about locking

Related posts about sql-server