I have a large migration script (about 2000 lines) that fails because of a deadlock on some metadata, and the lock types are SCH_S and SCH_M according to some xEvents data I
Can someone help me recreate this kind of scenario in single process?
There is a simple demo of this issue here.
BEGIN TRAN
go
CREATE TYPE dbo.OptionIDs AS TABLE( OptionID INT PRIMARY KEY )
go
DECLARE @OptionIDs dbo.OptionIDs;
go
ROLLBACK
It is certainly unusual to have a deadlock involving a single process and single resource.
The resource is metadatalock subresource="USER_TYPE" classid="user_type_id = 264"
The session already holds a SCH-M
metadata lock on a user defined type (probably as you created it earlier in the script) and this blocks an attempt to get a SCH-S
lock on the same object by the same session later.
The transaction name shown in the deadlock graph is @OptionIDs
- this is an internal system transaction that writes to the tempdb
transaction log when creating the instance of the table type corresponding with the DECLARE @OptionIDs
above. This is a separate transaction from the surrounding user transaction which is why the session is unexpectedly unable to get a SCH-S
lock despite already holding the SCH-M
lock.
This is blogged about by Aaron Bertrand here