代码之家  ›  专栏  ›  技术社区  ›  Haminteu

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

  •  0
  • Haminteu  · 技术社区  · 6 年前

    我有两张桌子:

    表1

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

    表2

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

    场景是:如果我更新 Table2 在…上 TID2 = 2 这个 LastStatus 在…上 Table1 不应该更新,因为上有一个最大日期 表2 具有 TID1=1 所以 最后状态 在…上 表1 只有在上有更新时才会更新 表2 和MAX Date在一起。

    目前,我只在 表2 .这对我没有影响 表1 .以下是我的代码:

    -- 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
    

    有人知道怎么解决这个问题吗?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Dale K    6 年前

    理想情况下,可以将两个表的插入/更新合并到一个存储过程中,在该存储过程中可以执行以下操作:

    -- 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';
    
        2
  •  0
  •   Haminteu    6 年前

    我找到了答案。。非常感谢你回答我的问题。

    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