0

在下面的代码中。一次只会执行一个“选择”语句。我希望能够更新任何选定行的“状态”并返回数据。这基本上可以防止在后端处理期间获取相同的记录。

谢谢!

-- Insert statements for procedure here
if(@BatchSize > -1 and @Priority > -1)
begin
    Select TOP(@BatchSize) *,ID 
    From CompingQueue 
    Where PriorityLevel=@Priority 
       and Status=35 
    order by PriorityLevel asc;
end
if(@BatchSize = -1 and @Priority = -1)
begin
    Select * From CompingQueue 
    Where Status=35 
    order by PriorityLevel asc;
end

if(@BatchSize = -1 and @Priority > -1)
begin
   Select * From CompingQueue 
   WHEre PriorityLevel=@Priority 
     and Status=35     
   order by PriorityLevel asc;
end
if(@BatchSize > -1 and @Priority = -1)
begin
    Select TOP(@BatchSize) * 
    From CompingQueue 
    Where Status=35 
    order by PriorityLevel asc;
end
--update CompingQueue set Status = 2 where ID=
-- Set the Status Flag for each job

结尾

4

5 回答 5

1

我会使用 DECLARE @tblResults TABLE (...)。将 SELECT 行插入到表变量中。从源表到 PK 上的表变量执行连接,将此连接用作 UPDATE 语句中的子句,然后将变量作为 query/proc/func 结果返回。

于 2013-03-22T19:26:02.357 回答
1

一种选择是仅UPDATE表并用于OUTPUT将更新的行存储在表变量中。然后,您可以SELECT进一步处理表变量中的数据。

文档中有一个示例。

于 2013-03-22T19:29:51.797 回答
0

像这样一次性完成它们怎么样:

Declare @NumRecs int
if @BatchSize > -1 Set @NumRecs = @BatchSize 
else Select @NumRecs = Count(*) From CompingQueue 
-- --------------------------
Declare @Ids table (id int primary key not null)
Insert @Ids(id)
Select top(@numRecs) id 
From CompingQueue 
Where Status=35 
   And PriorityLevel = Case 
      When @Priority > -1 Then @Priority 
      Else PriorityLevel End
Order by PriorityLevel asc;

 Select * From CompingQueue 
 Where Id In (Select id from @Ids);

 Update CompingQueue Set
    status = 2
 Where Id In (Select id from @Ids);
于 2013-03-22T19:41:28.723 回答
0

你想要这个OUTPUT子句。

http://msdn.microsoft.com/en-us/library/ms177564.aspx

听起来你想要类似的东西

UPDATE c
SET somestuff = something
OUTPUT DELETED.*
FROM CompingQueue c
WHERE someotherstuff

或者,如果您想要更新后数据,请使用INSERTED.*而不是DELETED.*.

于 2013-03-22T19:36:16.213 回答
0

SQL CTE 将为您的案例提供帮助。您正试图避免并发问题,因为多个进程可能会更新相同的记录。在您的查询中,您拥有最高批次,因此直接更新...输出可能不是最佳选择。CTE + xlock,rowlock会是更好的选择


;with Update_batch 
as 
(
  select top 10 * from compingqueue With (xlock, rowlock)
  order by PriorityLevel desc
)
update Update_batch
set ....=....
You can treat CTE as on-fly view, with (xlock, rowlock) , when rows are selected, an (xlock, rowlock) will be put on the row, which will make sure other processes could not even get the same rows.

于 2013-03-22T21:05:57.880 回答