我有三张桌子
userTable
包含以下行Id
,FirstName
,LastName
,Email
Product A
包含以下行Id
,UserId
(FK),startDate
Product D
包含以下行Id
,UserId
(FK),startDate
我想删除具有特定UserId的三个表中的行。
我想要实现的目标 -
查找给定电子邮件(select id from userTable where Email = 'abc.com')
的ID - 返回ID - 3
Delete from Product A where id = 3
Delete from Product D where id = 3
Delete from userTable where id = 3
我想创建一个脚本。
感谢任何帮助或学习参考会很棒。
答案 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
注意:如果你想做同样的事情,那么请去第一个。如果要从A
和D
表中删除相关用户记录,请转到使用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服务器中完成。