在mssql中同时删除和更新

问题描述 投票:0回答:3

我在mssql服务器上有一个删除工作。但我希望在删除之前更新另一个表。我有两个表通过“user_id”列连接,我的表名称是“UserInfo”和“AdvertInfo”,它们与user_id列连接。我在7天后删除giving_advert_day。但是当它被删除时,ı想增加(+1)user_advert_number列。如果在user_id中删除,从表中删除3或4等数据,则来自它们的连接数据将增加+ 3,+ 4或蚀刻。有办法吗?这是我的删除命令

Delete from AdvertInfo where advert_id In (
select advert_id from AdvertInfo
 where advert_begin_date <  DATEADD(day, -7, GETDATE()))
sql-server sql-update command sql-delete sql-job
3个回答
2
投票

你可以UPDATEJOIN

UPDATE u
SET u.user_advert_number = u.user_advert_number + 1
FROM UserInfo as u
INNER JOIN AdvertInfo AS a ON u.user_id = a.user_id
WHERE a.advert_begin_date <  DATEADD(day, -7, GETDATE()))

顺便说一下,你的删除子句可以写成如下:

Delete 
from AdvertInfo 
where advert_begin_date <  DATEADD(day, -7, GETDATE()))

没有必要使用IN谓词。


你也可以创建一个create a trigger来执行after delete,例如以你想要的方式更新列。


1
投票

使用下面的查询来实现您想要的:

DECLARE @Temp TABLE (
    [user_id] INT
)

DELETE i
OUTPUT deleted.[user_id] INTO @Temp
FROM AdvertInfo i
WHERE advert_begin_date <  DATEADD(day, -7, GETDATE())

UPDATE u
SET u.user_advert_number = u.user_advert_number + d.cnt
FROM UserInfo as u
    INNER JOIN (
        SELECT [user_id], COUNT([user_id]) AS cnt
        FROM @Temp
        GROUP BY [user_id]
    ) d ON d.[user_id] = u.[user_id]

1
投票

Merhaba Kaya,也许您可​​以按如下方式使用SQL OUTPUT clause您可能已经知道,在执行DELETE命令时,您可以将带有OUTPUT子句的受影响数据放入变量表中,如下面的示例所示,您可以在以后使用它

DECLARE @Deleted table (  
    user_id int
);  

DELETE FROM AdvertInfo
OUTPUT DELETED.user_id
INTO @Deleted 
WHERE advert_begin_date <  DATEADD(day, -7, GETDATE())

update u
set user_advert_number = isnull(user_advert_number,0) + 1
from UserInfo as u
inner join @Deleted d on d.user_id = u.user_id
© www.soinside.com 2019 - 2024. All rights reserved.