我想根据同一个表中其他行的存在从SQL Server 2000/2005表变量中删除行(如果存在具有相同日期的非0计数行,则删除所有0个计数行)。这是一个简化的示例,应该只删除首先添加的行:
declare @O table (
Month datetime,
ACount int NULL
)
insert into @O values ('2009-01-01', 0)
insert into @O values ('2009-01-01', 1)
insert into @O values ('2008-01-01', 1)
insert into @O values ('2007-01-01', 0)
delete from @O o1
where ACount = 0
and exists (select Month from @O o2 where o1.Month = o2.Month and o2.ACount > 0)
问题是我无法让SQL服务器接受表变量的o1别名(我认为由于“o1.Month = o2.Month
”匹配字段名称而需要别名)。错误是:
Msg 102,Level 15,State 1,Line 11
'o1'附近的语法不正确。
答案 0 :(得分:52)
在 FROM 语句之前指定别名 意思是,您要从别名表中删除。
delete o1
from @O as o1
where ACount = 0
and exists ( select Month
from @O o2
where o1.Month = o2.Month
and o2.ACount > 0)
结果
答案 1 :(得分:8)
试试这个,它应该工作(第一个FROM是可选的):
DELETE [FROM] @O
FROM @O o1
where ACount = 0
and exists (select Month from @O o2
where o1.Month = o2.Month and o2.ACount > 0)
理由是: 正如here所解释的那样,DELETE首先需要一个非别名表,一个可选的FROM可以在它之前。之后,如果需要执行JOIN,子查询等,可以在第二个FROM中的表上放置别名。