CTE在使用CTE表之前执行命令

时间:2014-10-07 10:26:44

标签: sql sql-server tsql

在选择CTE表之前,有没有办法编写任何类型的代码?

DECLARE @TestTable TABLE (ID INT ,name NVARCHAR)
INSERT INTO @TestTable VALUES (1,'a'),(2,'b'),(1,'c')
;WITH TempCte(name)
AS
(
SELECT name FROM @TestTable WHERE ID = 1
)
PRINT 'test'
SELECT * FROM TempCte

1 个答案:

答案 0 :(得分:1)

不,那是不可能做到的。如果你参考MSDN,那么:

A common table expression (CTE) can be thought of as a temporary result set 
that is defined within the execution scope of a SINGLE 
SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

所以基本上它是 SINGLE SELECT / INSERT / UPDATE / DELETE /或CREATE VIEW语句的范围,它保存CTE结果集。在该范围之后写的任何内容都无法访问此临时数据。您可以在此处阅读更多内容: http://msdn.microsoft.com/en-us/library/ms175972.aspx