在以下代码中。一次只能执行一个'Select'语句。我希望能够更新任何选定行的“状态”以及返回数据。这基本上可以防止在后端处理期间获取相同的记录。
谢谢!
-- 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
END
答案 0 :(得分:1)
我会使用DECLARE @tblResults TABLE(...)。将SELECT的行插入表变量中。执行从源表到PK上的表变量的连接,使用此连接作为UPDATE语句中的子句,然后将该变量作为查询/ proc / func结果返回。
答案 1 :(得分:1)
一个选项是仅UPDATE
表,并使用OUTPUT
将更新的行存储在表变量中。然后,您可以SELECT
或进一步处理表变量中的数据。
documentation中有一个例子。
答案 2 :(得分: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.*
。
答案 3 :(得分: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);
答案 4 :(得分:0)
SQL CTE将为您提供帮助。您正试图避免concurreny问题,因为多个进程可能会获得相同的记录进行更新。在您的查询中,您拥有最高批次,因此直接更新...输出可能不是最佳选择。 CTE + xlock,rowlock 将是更好的选择
;with Update_batch
as
(
select top 10 * from compingqueue With (xlock, rowlock)
order by PriorityLevel desc
)
update Update_batch
set ....=....
您可以将CTE视为动态视图,使用(xlock,rowlock),当选择行时,(xlock,rowlock)将被放置在该行上,将确保其他进程甚至无法获得相同的行。