SELECT查询后CTE中的数据更改

时间:2017-05-27 21:26:36

标签: sql sql-server common-table-expression

我有这样的查询:

USE [MyDataBase] 
GO
DECLARE @day DATE = '2017-05-18'
DECLARE @camp VARCHAR(500) = '9015';
WITH ODCALLS AS (SELECT * FROM [dbo].[ODCalls_2017_05]
   WHERE CONVERT(DATE, CallLocalTime) = @day AND LastCampaign = @camp AND CallType = 1
  )

SELECT COUNT(*) FROM ODCALLS -- this returns 2998 
SELECT DATEPART(HOUR, CallLocalTime) AS dHOUR, COUNT(*) AS [Calls Received]
  FROM ODCALLS
  GROUP BY DATEPART(HOUR, CallLocalTime)
  ORDER BY dHOUR -- this returns 24 rows as there are 24 hours in a day
SELECT COUNT(*) FROM ODCALLS -- this returns 2907

实例是SQL SERVER EXPRESS 2014,OdCalls_2017_05表中的数据不会改变,这里是结果的预览: enter image description here

我不知道为什么会这样,有人有任何解释吗?

由于

1 个答案:

答案 0 :(得分:2)

我很惊讶这完全奏效。公用表表达式就像临时表一样。该查询用作下一个查询的输入(如View可以),并且可以跨后续查询和CTE执行优化,因此CTE的结果集可能永远不会存在。

随后对CTE的调用不起作用,因为这违反了CTE的定义。有关详情,请参阅https://blogs.sentryone.com/aaronbertrand/backtobasics-ctes/