使用外键从多个表中删除行

时间:2017-01-11 03:53:19

标签: sql sql-server

我有三张桌子

  1. userTable包含以下行IdFirstNameLastNameEmail
  2. Product A包含以下行IdUserId(FK),startDate
  3. Product D包含以下行IdUserId(FK),startDate
  4. 我想删除具有特定UserId的三个表中的行。

    我想要实现的目标 -

    1. 查找给定电子邮件(select id from userTable where Email = 'abc.com')的ID - 返回ID - 3

    2. Delete from Product A where id = 3

    3. Delete from Product D where id = 3

    4. Delete from userTable where id = 3

    5. 我想创建一个脚本。

      感谢任何帮助或学习参考会很棒。

2 个答案:

答案 0 :(得分:1)

声明变量并将id保存到该变量。将Id用于删除查询。

DECLARE @Id INT;

SELECT @Id=id 
FROM userTable 
WHERE Email = 'abc.com'

DELETE FROM Product A WHERE id = @Id
DELETE FROM Product D WHERE id = @Id
DELETE FROM userTable WHERE id = @Id

但我猜你的情况下你有UserId作为FK所以你应该尝试这个:

DELETE FROM Product A WHERE UserId= @Id
DELETE FROM Product D WHERE UserId= @Id
DELETE FROM userTable WHERE id = @Id 

注意:如果你想做同样的事情,那么请去第一个。如果要从AD表中删除相关用户记录,请转到使用FK删除记录的第二种方法。

答案 1 :(得分:0)

从我可以从你的问题中收集到你想要的东西:

DELETE FROM
    userTable,
    ProductA,
    ProductB
WHERE
    userTable.Id = (select Id from userTable where Email like 'abc.com') AND
    userTable.Id = ProductA.Id AND
    userTable.Id = ProductB.Id;

WHERE子句中子查询中的电子邮件将是您的输入参数

免责声明:从Sybase / SQL Anywhere背景来看,这是可能的,我不确定它是否可以在SQL服务器中完成。