防止存储过程和视图执行之间的死锁

时间:2019-04-10 12:28:04

标签: sql sql-server

我们有一个存储过程,可将数据插入3个表中(某些部分存储在单独的表中,更新订单的版本):

CREATE PROCEDURE [dbo].[SpecialOrders_Insert]
    @lastName nvarchar(100),
    @firstName nvarchar(100),
    @productId int,
    @blabla nvarchar(100),
    @special1 nvarchar(100),
    @special2 nvarchar(100),
    @special3 nvarchar(100),
    @changedBy int
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    DECLARE @lastChangedDate datetime = GetDate();
    DECLARE @identity int

    BEGIN TRAN;

        -- Place Order-Head
        INSERT INTO dbo.Orders_H 
                    (LastName
                    , FirstName
                    , ProductId) 
        VALUES 
                    (@lastName,
                    @firstName,
                    @productId);

        SET @identity = SCOPE_IDENTITY();

        -- Place Order-Data (expect lot more data here)
        INSERT INTO dbo.Orders_D
                    (ParentId
                    , Blabla
                    , LastChangedDate
                    , LastChangedBy
                    , ValidFrom
                    , ValidTo)
        VALUES
                    (@identity
                    , @blabla
                    , @lastChangedDate
                    , @changedBy
                    , @lastChangedDate
                    , null);


        INSERT INTO dbo.SpecialOrders_D
                    (ParentId
                    , Special1
                    , Special2
                    , Special3
                    , LastChangedDate
                    , LastChangedBy
                    , ValidFrom
                    , ValidTo)
        VALUES
                    (@identity
                    , @special1
                    , @special2
                    , @special3
                    , @lastChangedDate
                    , @changedBy
                    , @lastChangedDate
                    , null);

    COMMIT TRAN;
END

以及一些总是读取当前版本的视图,例如:     创建视图[dbo]。[SpecialOrders] AS

    SELECT 
        -- Orders_H
        h.Id, h.LastName, h.FirstName, h.ProductId,

        -- Orders_D (expect lot more columns here)
        d.Blabla, 

        -- Specialorders (also here more data expected)
        s.Special1, s.Special2, s.Special3

    FROM Orders_H h
         left join Orders_D d ON h.Id = d.ParentId
         left join SpecialOrders_D s ON d.ParentId = s.ParentId

    WHERE d.ValidTo is null and s.ValidTo is null

当前,当SP插入数据并且视图同时读取数据时,我们陷入死锁。 sp对Orders_H持有排他锁,而视图对Orders_D持有共享锁。

如何修改视图,以保证按正确的顺序读取数据:Orders_H,Orders_D,Specialorders?

0 个答案:

没有答案