为什么while循环没有遍历整个集合?

时间:2019-04-27 08:51:59

标签: sql sql-server tsql stored-procedures sql-server-2012

我有2张桌子。

InspectionUTG和InspectionHistoryUTGTML。

select distinct InspectionUTGID
from InspectionHistoryUTG

返回

5196
5197
5198
5199
5200

-步骤2:从上述结果中获取一个ID,例如:5260

select top 1 UserTmin, RLTMin
from InspectionHistoryUTGTML
where InspectionUTGID = 5260 and RLTMin is not null
order by RLTMin 

-步骤3:获取上面查询(即33.17)返回的UserTmin,并在下面针对下面查询中的TMin使用它

update InspectionHistoryUTG set
  TMin = 33.17
where InspectionUTGID = 5260

现在我要做的是

create table #TableInspectionsUTGs
(
    InspectionUTGID int
)

Insert into #TableInspectionsUTGs
  select distinct InspectionUTGID from InspectionHistoryUTG

Select #TableInspectionsUTGs.InspectionUTGID from #TableInspectionsUTGs

While ((Select Count(#TableInspectionsUTGs.InspectionUTGID) from #TableInspectionsUTGs) > 0)
Begin
  select top 1 UserTmin ,RLTMin
  from InspectionHistoryUTGTML 
  where InspectionUTGID = #TableInspectionsUTGs.InspectionUTGID and RLTMin is not null order by RLTMin 
End

但是它不起作用。我只想使用针对InspectionUTGID的第一个查询返回的每个InspectionUTGID 在第二个查询的where子句中,然后对第二个查询中的UserTmin使用第三个查询中的TMin

1 个答案:

答案 0 :(得分:0)

如果我了解您要完成的工作,即根据TminInspectionHistoryUTG的最新值来更新UserTmin中的InspectionHistoryUTGTML,那么您将要以程序方式,就像您在编写常规代码一样。但是,在编写SQL时,需要采用基于集合的编码,因为这就是SQL Server的工作方式和执行方式。

因此,您要完成的任务可能可以通过以下一条SQL更新语句来实现:

declare @InspectionHistoryUTG table (InspectionUTGID int, TMin int);
declare @InspectionHistoryUTGTML table (InspectionUTGID int, UserTmin int, RLTMin int);

insert into @InspectionHistoryUTG (InspectionUTGID)
  select 1
  union all select 2
  union all select 3;

insert into @InspectionHistoryUTGTML (InspectionUTGID, RLTMin, UserTmin)
  select 1, 1, 1
  union all select 1, 2, 2
  union all select 1, 3, 3
  union all select 2, 1, 3
  union all select 2, 2, 2
  union all select 2, 3, 1
  union all select 3, 1, 2
  union all select 3, 2, 3
  union all select 3, 3, 1;

--select * from @InspectionHistoryUTG;
--select * from @InspectionHistoryUTGTML;

update IH set
  TMin = (
      select top 1 IHT.UserTmin
      from @InspectionHistoryUTGTML IHT
      where IHT.InspectionUTGID = IH.InspectionUTGID and IHT.RLTMin is not null
      order by IHT.RLTMin
    )
from @InspectionHistoryUTG IH
-- Following where clause won't update if a single null TML record exists as per OPs comment
where not exists (
  select 1
  from @InspectionHistoryUTGTML IHT
  where IHT.InspectionUTGID = IH.InspectionUTGID and IHT.RLTMin is null
)

select * from @InspectionHistoryUTG;
--select * from @InspectionHistoryUTGTML;

我们仅对InspectionHistoryUTG使用常规更新语句,对InspectionHistoryUTGTML使用子查询,以获取TMin当前值InspectionUTGID的{​​{1}}所需值。 / p>

因此,我们无需一次多次选择InspectionHistoryUTG来更新@echo off SET var=%cd% cd C:\IBM\WebSphere\AppServer\profiles\profile1\bin wsadmin -language jython -user wasadmin -password pass -f C:/dev/wdrSample/sample.py C:/dev/wdrSample/config.ini cd %var% ,而是一次完成全部操作。

注意:这也是您以后提出问题的方式,因为这意味着愿意提供帮助的人们可以将SQL复制并粘贴到他们的查询分析器中,并开始使用有效的示例数据进行处理。

相关问题