异常','附近的语法不正确。在SQL Server中

时间:2018-06-25 06:07:15

标签: sql-server

试图从两个表中删除数据并出现错误Incorrect syntax near ','.

DELETE tblItem, tblCategory
FROM tblCategory
INNER JOIN tblItem
WHERE tblCategory.category_id = tblItem.fk_category

更新

enter image description here

怎么了?

2 个答案:

答案 0 :(得分:2)

DELETE一次只能从一个表中删除,因此您将必须按照正确的顺序执行两个单独的delete语句:

DELETE
FROM tblItem
WHERE fk_category IN (...)

然后

DELETE
FROM tblCategory
WHERE category_id = (...)

首先,我们可以尝试删除属于某些目标类别的所有项目。然后,一旦删除了这些子记录,我们就可以删除父类别记录。

一种更好的解决方法是使用类似ON DELETE CASCADE的方法,这意味着如果要删除tblCategory中的父类别,SQL Server会自动将该删除传播到所有子项记录中在tblItem中。

答案 1 :(得分:1)

尝试这样

   DELETE from 
      FROM tblCategory where category_id  in (select  fk_category from  tblItem  )


   DELETE from 
      FROM tblItem  where fk_category in (select  category_id  from  tblCategory )