Skip to content
Advertisement

SQL Update Only when Max Date reached

I’ve two tables like:

Table1

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

Table2

-----------------------------------------
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. So LastStatus on Table1 will only updated if there’s an update on Table2 with MAX Date.

Currently, I only work on Table2. It doesn’t effect to 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?

Advertisement

Answer

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';
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement