查询占用太多

时间:2013-04-08 22:34:29

标签: sql

我正在尝试在条件返回结果时执行更新,问题是当我测试查询时它永远不会完成。 这是查询;

While(select COUNT(*) from Agreement as agr where agr.Id in (
  select toa.Id from Agreement_TemporaryOnceAgreement as toa where toa.Executed =1)
and agr.EndingDate is null) > 0
begin
DECLARE @AgreementID int;
SET @AgreementID = 
(
select top 1 agr.id from Agreement as agr where agr.Id in (
  select toa.Id from Agreement_TemporaryOnceAgreement as toa where toa.Executed =1)
and agr.EndingDate is null
)
update Agreement SET EndingDate = (
  select tado.Date from TemporaryAgreementsDateOfExecution tado
    where tado.AgreementId = CAST(@AgreementID AS INT))
where Agreement.Id = CAST(@AgreementID AS INT);
end;

1 个答案:

答案 0 :(得分:0)

您不需要循环。一个类似于此的更新查询应该可以完成工作。

update a
set EndingDate = tado.date
from Agreement a join TemporaryAgreementsDateOfExecution tado
on a.AgreementId = tado.AgreementId

join Agreement_TemporaryOnceAgreement toa
on a.Id = toa.id

where EndingDate is null
and toa.Executed = 1

根据您使用的RDBMS,可能会略有不同。