如何更新从另一个表中删除的行?

时间:2013-11-10 14:42:27

标签: sql sql-server sql-server-2008

我有两张桌子:

  1. users user_id, status
  2. changes user_id, type
  3. 我想从changes删除一行,如果type = 5,则设置:

    users.status = NULL Where users.user_id = changes.user_id
    

    我该怎么做?

2 个答案:

答案 0 :(得分:2)

试试这个:

-- table variable to store deleted changes
declare @deleted_changes table(user_id int, [type] int);

-- saving info from deleted changes into temp table
delete from changes 
output deleted.user_id, deleted.[type] into @deleted_changes;
-- where [some condition]

-- updating users only if corresponding changes with type = 5 were deleted
update users
set status = null
where user_id in (select user_id from @deleted_changes where [type] = 5);

答案 1 :(得分:0)

对于DELETE,你的意思是......

DELETE FROM Changes WHERE type = 5

尝试以下更新....

UPDATE  u
SET     u.status = NULL
FROM    users u
        INNER JOIN changes c ON u.user_id = c.user_id