我需要从两个表中删除一行记录,它们通过ID关联,但不存在适当的主外键关系(这个数据库没有外键!)。
这两个表应该是一对一的关系。我不知道为什么它们没有被放在同一个表中,但我不能更改它。
人员
PersonId | Name | OwnsMonkey
----------------------------
1 Jim true
2 Jim false
3 Gaz true
信息
PersonId | FurtherInfo
-----------------------------
1 Hates his monkey
2 Wants a monkey
3 Loves his monkey
为了决定删除什么,我需要找到一个用户名以及他们是否拥有一只猴子。
Select PersonId from People where Name = 'Jim' and OwnsMonkey = 'false'
因此,我使用这个思路进行了两次单独的语句,首先从 Info
中删除,然后再从 People
中删除。
delete from Info where PersonId = (Select PersonId from People where Name = 'Jim' and OwnsMonkey = 'false');
delete from People where PersonId = (Select PersonId from People where Name = 'Jim' and OwnsMonkey = 'false');
我在StackOverflow上找到了一个有前途的答案:这里。
delete a.*, b.*
from People a
inner join Info b
where a.People = b.Info
and a.PersonId =
(Select PersonId from People where Name = 'Jim' and OwnsMonkey = 'false')
但在 Sql Server (2012) 中会产生语法错误,我尝试了不使用别名的情况,但好像无法同时删除两个表。
Incorrect syntax near ','
。 - jamheadartTRY/CATCH
是必要的,但不足以保证数据完整性。你需要将其与BEGIN TRANSACTION
+COMMIT
结合使用(在CATCH
块中使用ROLLBACK
)。 - Dai