我想根据同一个表中其他行的存在情况从 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 Server 接受表变量的 o1 别名(并且我认为由于“o1.Month = o2.Month
”匹配字段,需要别名名称)。错误是:
Msg 102, Level 15, State 1, Line 11
Incorrect syntax near 'o1'.
最佳答案
在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)
结果
关于sql - Delete From 语句中带有别名的表变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/597513/