简体   繁体   English

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

[英]SQL delete from multiple tables with foreign keys

I have 2 tables which are connected by foreign keys, the fields UploadID . 我有2个表通过外键连接,字段UploadID

I want to delete some rows from the database. 我想从数据库中删除一些行。 I tried several SQL queries which won't work. 我尝试了几个不起作用的SQL查询。

Now I have this one which I think should do the trick but is get the error: 现在我有一个我认为应该做的技巧,但是得到了错误:

Msg 102, Level 15, State 1, Line 2 Msg 102,Level 15,State 1,Line 2
Incorrect syntax near ','. ','附近的语法不正确。

DELETE 
  a, b FROM [Uploads] as a, 
  [OrderLines] as b 
  WHERE [Uploads].UploadID < 53436;

any thoughts? 有什么想法吗?

You can only delete from 1 table at a time in SQL Server 您只能在SQL Server中一次从1个表中删除

However if you have your keys setup with cascade delete then if you delete them from the parent table, then they will be deleted automatically from the child tables 但是,如果您使用cascade delete设置了密钥,那么如果从父表中删除它们,那么它们将从子表中自动删除

otherwise you need to run two delete statements, first one for the child rows, then one for the parent rows 否则你需要运行两个delete语句,第一个用于子行,然后一个用于父行

something like this...however I am puzzled.. where is your JOIN condition? 这样的事......但我很困惑...... 你的JOIN条件在哪里?

DELETE 
  b FROM [Uploads] as a, 
  [OrderLines] as b 
  WHERE [Uploads].UploadID < 53436;

DELETE 
  [Uploads] 
  WHERE [Uploads].UploadID < 53436;

I would prefer to use a new style ANSI JOIN..like the following 我更喜欢使用ANSI JOIN的新样式。如下所示

DELETE 
  b FROM [Uploads] as a, 
  JOIN [OrderLines] as b on A.SomeColumns = b.SomeColumn
  WHERE a.UploadID < 53436;

you pretty much have a cartesian product(cross join) 你几乎有笛卡尔积(交叉连接)

Your design sounds like you could use the CASCADE feature of TSQL. 您的设计听起来像是可以使用TSQL的CASCADE功能。 Basically, this will allow you to design your table so that deleting an Upload will always clear out the Orderline as well (or the other way around). 基本上,这将允许您设计您的表,以便删除Upload将始终清除Orderline (或相反)。

http://msdn.microsoft.com/en-us/library/aa933119(v=SQL.80).aspx http://msdn.microsoft.com/en-us/library/aa933119(v=SQL.80).aspx

(First off let me say I know the DB) (首先让我说我知道DB)

I know you want to delete the old uploads. 我知道你要删除旧的上传。 Instead of doing so,, rewrite the C#/asp.NET code to show only uploads that are younger then 40 days. 而不是这样做,重写C#/ asp.NET代码,只显示40天以下的上传。

You need to delete from the child table first then parent. 您需要先从子表中删除父项。

CREATE TABLE #TEMPTABLE(ID INT)
INSERT INTO #TEMPTABLE(ID)
SELECT UPLOADID FROM ORDERLINES WHERE UPLOADID < 53436;

DELETE FROM ORDERLINES WHERE UPLOADID < 53436;
DELETE FROM UPLOADS WHERE UPLOADID IN (SELECT ID FROM #TEMPTABLE)

DROP TABLE #TEMPTABLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM