对SQL语句有一个奇怪的问题。我正在使用WITH
语句来收集树结构的父行和子行。
然后我要删除父母,只删除他们的孩子。
我的代码如下(在存储过程中):
DECLARE @AssignmentIds TABLE
(
AssignmentIds int
);
with DeleteTree(AssignmentID)
as
(
select AssignmentID
from Assignment
where AssignmentID = @AssignmentID
union all
select a.AssignmentID
from Assignment a
join DeleteTree d on a.ParentID = d.AssignmentID
)
/* insert results of above with into table var*/
insert into @AssignmentIds
select AssignmentID from DeleteTree
/*This select returns the CORRECT Ids!*/
/*SELECT * from @AssignmentIds*/
/*Delete Roster Info*/
delete from [dbo].[Roster]
where [AssignmentId] in (select AssignmentId from @AssignmentIds)
/*Delete Assignments*/
delete from [dbo].[Assignment]
where [AssignmentID] in (select AssignmentID from @AssignmentIds)
奇怪的是,如果我对with的结果运行一个select,我会正确得到一个正确的赋值id的列表。
但是当我运行delete
语句时,它会删除赋值表中的所有行,而不只是删除with语句中的Ids!
答案 0 :(得分:0)
我希望这有助于某人。但是由于最后删除语句中的拼写错误(@AssignmentIds表var的列名错误地“AssignmentIds”而不是“AssignmentId”)SQL Parser没有给出错误,而是删除了名单中的所有行和分配表。
我仍然不确定为什么会这样,而不是删除任何东西,但可能有其他人有答案。
所以我学到的经验是在删除语句中查找拼写错误。否则男人会吓人!