简体   繁体   English

SQL 仅在达到最大日期时更新

[英]SQL Update Only when Max Date reached

I've two tables like:我有两张桌子,例如:

Table1表格1

-----------------------------------------
TID1     Name      Status        LastStatus         
-----------------------------------------
1        A         1             3

Table2表2

-----------------------------------------
TID2     TID1     oDate          Status
-----------------------------------------
1        1        2020-04-01     1
2        1        2020-04-03     2
3        1        2020-04-05     3

The scenario is: If I update the Table2 on TID2 = 2 , the LastStatus on Table1 shouldn't be updated because there's a MAX Date on Table2 with TID1=1 .场景是:如果我在TID2 = 2上更新Table2 ,则不应更新Table1上的LastStatus ,因为Table2上有一个TID1=1的 MAX Date 。 So LastStatus on Table1 will only updated if there's an update on Table2 with MAX Date.因此,表 1 上的LastStatus只会在Table1 Table2上的更新为 MAX 日期时才会更新。

Currently, I only work on Table2 .目前,我只在Table2上工作。 It doesn't effect to Table1 .它对Table1没有影响。 Below are my code:以下是我的代码:

-- Insert Statement
Declare @TID1 int, @oDate DateTime, @Status int;
Set @TID1 = 1;
Set @oDate = '2020-04-05';
Set @Status = 3;
Insert into Table2 (TID1, oDate, Status) values (@TID1, @oDate, @Status)

-- Update Statement (Example only - if there's a row to be updated)
Update Table2 Set TID1=@TID1, oDate=@oDate, Status=@Status
where TID2 = 3

Does anyone know how to solve this?有谁知道如何解决这个问题?

Ideally you would combine the inserts/updates to both tables in a stored procedure where you would do something like the following:理想情况下,您将在存储过程中将两个表的插入/更新结合起来,您可以在其中执行以下操作:

-- Insert into Table2
insert into dbo.Table2 (TIDI1, oDate, [Status])
  select @TIDI1, @oDate, @Status;

-- OR

-- Update Table2
update dbo.Table2 set
  TID1 = @TIDI1
  , oDate = @oDate
  , [Status] = @Status
where TID2 = @TID2;

-- Then update table1 if the date we just added is the latest or more recent
update dbo.Table1 set
  LastStatus = @Status
where TID1 = @TIDI1
and @oDate >= (select max(oDate) from dbo.Table2 T2 where T2.TID1 = @TID1);

if @@rowcount = 0 print 'Do nothing';

Well, I found my answer.. Thank you so much for answering my question.好吧,我找到了答案。非常感谢您回答我的问题。

update      ActivityPlanHistory
    set         ActivityPlanId = ActivityPlanId, UpdateDate = @UpdateDate, 
                StatusId = @StatusId, Remarks = @Remarks
    where       ActivityPlanHistoryId = @ActivityPlanHistoryId;

    if (select max(UpdateDate) from ActivityPlanHistory where ActivityPlanId = @ActivityPlanId) <= @UpdateDate
        begin 
            update      ActivityPlan 
            set         LastStatus = @StatusId, LastUpdateDate = @UpdateDate, 
                        LastRemarks = @Remarks
            where       ActivityPlanId = @ActivityPlanId
        end
    else
        begin
            print 'do nothing';
        end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM