8

Khá một câu hỏi đơn giản. Trong SQL 2008 nếu tôi có một thủ tục được lưu trữ (xem bên dưới) để tôi có thể chạy nguy cơ của một điều kiện cuộc đua giữa hai câu lệnh đầu tiên hay thủ tục lưu trữ đặt một khóa trên những thứ nó chạm như giao dịch?Các thủ tục lưu trữ có khóa các bảng/hàng không?

ALTER PROCEDURE [dbo].[usp_SetAssignedTo] 
    -- Add the parameters for the stored procedure here 
    @Server varchar(50), 
    @User varchar(50), 
    @UserPool varchar(50) 
AS 
BEGIN 
    SET NOCOUNT ON; 
    Declare @ServerUser varchar(50) 

    -- Find a Free record 
    SELECT top 1 @ServerUser = UserName 
    from ServerLoginUsers 
    where AssignedTo is null and [TsServer] = @Server 

    --Set the free record to the user 
    Update ServerLoginUsers 
    set AssignedTo = @User, AssignedToDate = getdate(), SourcePool = @UserPool 
    where [TsServer] = @Server and UserName = @ServerUser 

    --report record back if it was updated. Null if it was not available. 
    select * 
    from ServerLoginUsers 
    where [TsServer] = @Server 
     and UserName = @ServerUser 
     and AssignedTo = @User 
END 

Trả lời

3

Bạn có thể nhận được điều kiện chủng tộc.

Nó có thể được thực hiện trong một tuyên bố:

  • Bạn có thể gán vào một UPDATE
  • Các gợi ý khóa cho phép một quá trình để skip hàng này
  • Mệnh đề OUTPUT trả về dữ liệu cho người gọi

Hãy thử điều này ... (chỉnh sửa: holdlock đã xóa)

Update TOP (1) ServerLoginUsers WITH (ROWLOCK, READPAST) 
OUTPUT INSERTED.* 
SET 
    AssignedTo = @User, AssignedToDate = getdate(), SourcePool = @UserPool 
WHERE 
    AssignedTo is null and [TsServer] = @Server -- not needed -> and UserName = @ServerUser 

Nếu không, bạn có thể cần một riêng biệt chọn

Update TOP (1) ServerLoginUsers WITH (ROWLOCK, READPAST) 
SET 
    -- yes, assign in an update 
    @ServerUser = UserName, 
    -- write 
    AssignedTo = @User, AssignedToDate = getdate(), SourcePool = @UserPool 
OUTPUT INSERTED.* 
WHERE 
    AssignedTo is null and [TsServer] = @Server -- not needed -> and UserName = @ServerUser 

SELECT ... 

Xem này xin vui lòng cho biết thêm: SQL Server Process Queue Race Condition

+0

tuyên bố sản lượng cần phải được đặt sau các thiết lập cho đúng cú pháp –

+0

tôi sử dụng ví dụ đầu tiên của bạn nhưng tôi đã nhận được lỗi 'Bạn chỉ có thể chỉ định khóa READPAST trong các mức cô lập READ COMMITTED hoặc REPEATABLE READ.' khi tôi chạy nó. –

+0

Ah OK, hãy thả GIỮ HOLDLOCK rồi – gbn

Các vấn đề liên quan