如何根据特定条件更新SQL中的两个表

时间:2014-01-11 18:40:40

标签: sql sql-server sql-server-2012

我有两张表Table1Table2

  • Table1包含ID (UniqueIdentifier) PK, IsActive (bit), ExpiryDate (DateTime), LastUpdateDT (Datetime)

  • Table2包含ID (uniqueIdentifier) PK, Table1ID (FK to Table1), IsActive (bit), LastUpdateDt (datetime)

Table2中有多行指向Table1的相同PK。

现在我宣布了一个变量@Now = Getdate()。我想找到Table1中IsActive = 1ExpiryDate < @Now的所有ID。使用这些ID我想将两个表中的IsActive标志和LastUpdateDt分别更新为0和@Now

如何在SQL中实现此逻辑?

此时Table1中的多行可以满足此条件。

2 个答案:

答案 0 :(得分:0)

DECLARE @Now DATETIME
SET @Now = GETDATE()

首先更新Table2

Update Table2
Set IsActive=0,
LastUpdateDT=@Now
WHERE Table1ID in (SELECT ID FROM Table1 WHERE IsActive = 1 AND ExpiryDate < @Now)

立即更新表1

Update Table1
Set IsActive=0,
LastUpdateDT=@Now
WHERE IsActive = 1 AND ExpiryDate < @Now

答案 1 :(得分:0)

CREATE TABLE #temp(ID UniqueIdentifier);

DECLARE @Now DATETIME = Getdate();

UPDATE Table1
 SET IsActive = 0,
     LastUpdateDt = @Now
OUTPUT inserted.ID INTO #temp(ID)    
WHERE IsActive = 1 and ExpiryDate < @Now

UPDATE Table2
 SET IsActive = 0,
     LastUpdateDt = @Now   
WHERE IsActive = 1 and ExpiryDate < @Now
AND Table1ID IN (SELECT ID
                 FROM #temp)

DROP TABLE #temp