1

我有一个返回唯一行的 SQL 脚本。我想更新该行中的一列和不同表中的计数器

我模拟了一种工作项队列,当从队列中选择一个元素时,它的状态设置为“正在执行”,但我还想跟踪选择了多少具有特定优先级的项目。

以下是没有用于计数的表的脚本

IF OBJECT_ID(N'[Queue]', N'U') IS NOT NULL 
    DROP TABLE [Queue]

CREATE TABLE [Queue](
    [ID]        int IDENTITY(1,1) NOT NULL,
    [Priority]  int NOT NULL default 3,
    [State]     int NOT NULL default 0,
    [Command]   nvarchar(max),    
    [Queued]    datetime2 NOT NULL default GetDate(),
    [Assigned]  datetime2 NULL
) 

INSERT INTO [Queue] ([Command], [Priority], [Queued])    VALUES 
    ('systeminfo', 1, DATEADD(MILLISECOND, -40, GETDATE())),
    ('systeminfo', 2, DATEADD(MILLISECOND, -30, GETDATE())),
    ('systeminfo', 1, DATEADD(MILLISECOND, -20, GETDATE())),
    ('systeminfo', 3, DATEADD(MILLISECOND, -20, GETDATE()))
GO

IF OBJECT_ID(N'Dequeue', N'P') IS NOT NULL 
    DROP PROCEDURE Dequeue
GO

CREATE PROCEDURE Dequeue
AS
    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ

    UPDATE selected
    SET [State] = 1, Assigned = GETDATE()
    OUTPUT inserted.*
    FROM (
        SELECT TOP(1) * 
        FROM [Queue] 
        WHERE [State] = 0 
        ORDER BY [Priority] ASC, [Queued] ASC
    ) selected

存储过程中的更新语句现在也应该执行类似的操作

UPDATE [Counter] 
SET [Counter].[Count] = [Counter].[Count] + 1 
WHERE [Counter][Priority] = selected.[Priority]

我是否必须将选定的行临时存储在临时表或变量中,还是有更优雅的方式?

4

2 回答 2

1

您可以将选项与表类型的变量一起使用

  DECLARE @Priority TABLE (Priority int)

  UPDATE selected
    SET [State] = 1, Assigned = GETDATE()
    OUTPUT inserted.Priority INTO @Priority(Priority)
    FROM (
          SELECT TOP(1) * 
          FROM [Queue] 
          WHERE [State] = 0 
          ORDER BY [Priority] ASC, [Queued] ASC
          ) selected

 UPDATE c
   SET c.[Count] = ISNULL(c.[Count], 0) + 1
   FROM [Counter] c JOIN @Priority p ON c.[Priority] = p.[Priority]
于 2013-03-20T22:00:08.373 回答
0

您是否尝试过向 Queue 表添加触发器以在 Counter 表上运行更新?

于 2013-03-20T19:39:43.940 回答