Skip to content

Instantly share code, notes, and snippets.

@nchammas
Created March 23, 2012 15:52
Show Gist options
  • Save nchammas/2172061 to your computer and use it in GitHub Desktop.
Save nchammas/2172061 to your computer and use it in GitHub Desktop.
Updating child row does not lock parent row in SQL Server
-- Tested on SQL Server 2008 R2
-- Isolation level is READ COMMITTED
--
-- Session 1
--
CREATE TABLE dbo.parent (
parent_id INT NOT NULL PRIMARY KEY
, value VARCHAR(50) NOT NULL
);
CREATE TABLE dbo.child (
child_id INT NOT NULL PRIMARY KEY
, parent_id INT NOT NULL
, value VARCHAR(50) NOT NULL
, CONSTRAINT FK_child_parent_id FOREIGN KEY (parent_id) REFERENCES dbo.parent(parent_id)
);
INSERT INTO dbo.parent
(parent_id, value)
VALUES
(1, 'howdy')
, (2, 'check it out');
;
INSERT INTO dbo.child
(child_id, parent_id, value)
VALUES
(1, 1, 'there')
, (2, 1, 'mang')
, (3, 2, 'dude')
;
BEGIN TRANSACTION;
UPDATE dbo.child
SET value = 'over there'
WHERE child_id = 1;
--ROLLBACK TRANSACTION;
--DROP TABLE dbo.child;
--DROP TABLE dbo.parent;
--
-- Session 2
--
UPDATE dbo.parent
SET value = 'hey you'
WHERE parent_id = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment