一个更新两个表的SQL语句

时间:2013-03-20 19:32:17

标签: sql tsql

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

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

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

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语句也应该像

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用带表类型

的变量的选项
  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]