您的DELETE
陈述不引用aDeleteVariable
. 该id
列仅存在于 的上下文中aDeleteVariable
。
你需要加入aDeleteVariable
你的DELETE
陈述。此外,您不能重用公用表表达式,因此您必须复制它。
请参阅此SQL Fiddle(带有简化的架构/表名称),但以下是您想要的。
WITH aDeleteVariable AS (SELECT TOP 1 FooID as id
FROM [BSystem].[Foo].[bar] order by CreateTimeUTC desc)
DELETE FB
FROM [BSystem].[Foo].[fooBar] AS FB
INNER JOIN aDeleteVariable AS DV ON (FB.FooID = DV.id);
WITH aDeleteVariable AS (SELECT TOP 1 FooID as id
FROM [BSystem].[Foo].[bar] order by CreateTimeUTC desc)
DELETE B
FROM [BSystem].[Foo].[bar] AS B
INNER JOIN aDeleteVariable AS DV ON (B.FooID = DV.id);
当然,加入 to 后aDeleteVariable
,您不需要id
别名。以下将起作用。
WITH aDeleteVariable AS (SELECT TOP 1 FooID
FROM [BSystem].[Foo].[bar] order by CreateTimeUTC desc)
DELETE FB
FROM [BSystem].[Foo].[fooBar] AS FB
INNER JOIN aDeleteVariable AS DV ON (FB.FooID = DV.FooID);
WITH aDeleteVariable AS (SELECT TOP 1 FooID
FROM [BSystem].[Foo].[bar] order by CreateTimeUTC desc)
DELETE B
FROM [BSystem].[Foo].[bar] AS B
INNER JOIN aDeleteVariable AS DV ON (B.FooID = DV.FooID);
鉴于有两个单独的公用表表达式,存在竞争条件,并且第二个表达式可能返回不同的FooID
(或者当您将其适应N
记录时返回多个)。您可能希望将 ID 选择到表变量中,而不是使用公用表表达式。以下应该工作。
DECLARE @DeleteVariable TABLE (FooID INT);
INSERT INTO @DeleteVariable (FooID)
SELECT TOP 1 FooID FROM [BSystem].[Foo].[bar]
ORDER BY CreateTimeUTC DESC;
DELETE FB
FROM [BSystem].[Foo].[fooBar] AS FB
INNER JOIN @DeleteVariable AS DV ON (FB.FooID = DV.FooID);
DELETE B
FROM [BSystem].[Foo].[bar] AS B
INNER JOIN @DeleteVariable AS DV ON (B.FooID = DV.FooID);