SQL Server - 如何使用一个CTE进行多个查询?

时间:2015-07-12 22:23:44

标签: sql sql-server

如何为不同的查询使用一个cte。下面是一个使用cte删除一些记录的例子

    WITH CTE AS (
       SELECT FirstName, LastName, count(*) FROM Employee
       GROUP BY FirstName, LastName
       HAVING count(*) > 1
    )
    DELETE FROM SomeOtherTable as sot
    WHERE sot.FirstName = cte.FirstName and sot.LastName = cte.LastName;

我想知道如何将此cte用于其他查询,而无需重写cte。我在这下面是我想要实现的,但当然不起作用。

WITH CTE AS (
SELECT FirstName, LastName, count(*) FROM Employee
GROUP BY FirstName, LastName
HAVING count(*) > 1
)
DELETE FROM SomeOtherTable as sot
WHERE sot.FirstName = cte.FirstName and sot.LastName = cte.LastName;
INSERT INTO PeopleTable (FirstName,LastName) 
SELECT cte.FirstName, cte.LastName from cte;

查询描述只是一个例子!问题是如何使用一个cte进行多个查询?请不要复制cte。这正是我想要避免的。 TY非常提前帮助。

1 个答案:

答案 0 :(得分:4)

使用TABLE变量和OUTPUT Clause (Transact-SQL)

DECLARE @Deleted TABLE
(
    FirstName VARCHAR(255),
    LastName VARCHAR(255)
)

WITH CTE AS (
    SELECT FirstName, LastName, count(*) FROM Employee
    GROUP BY FirstName, LastName
    HAVING count(*) > 1
)
DELETE FROM SomeOtherTable as sot
OUTPUT deleted.FirstName, deleted.LastName INTO @Deleted
WHERE sot.FirstName = cte.FirstName and sot.LastName = cte.LastName;

INSERT INTO PeopleTable (FirstName,LastName) 
SELECT FirstName, LastName from @Deleted;

或者,甚至更好,正如@Hart在评论中建议的那样,将OUTPUT值直接插入另一个表

WITH CTE AS (
    SELECT FirstName, LastName, count(*) FROM Employee
    GROUP BY FirstName, LastName
    HAVING count(*) > 1
)
DELETE FROM SomeOtherTable as sot
OUTPUT deleted.FirstName, deleted.LastName INTO PeopleTable (FirstName,LastName) 
WHERE sot.FirstName = cte.FirstName and sot.LastName = cte.LastName;