使用CTE结果填充临时表?

时间:2015-01-15 20:22:42

标签: sql-server common-table-expression

我有2个CTE,他们两个都为我选择了一些记录。一个是X,另一个是Y.另一方面,我有2个与CTE同名的临时表。我想用CTE结果填充这些临时表。最后我想在一个结果中显示这些临时表。 我的问题是我只能在这里使用CTE数据源一次  是我的代码

        use fidilio
;WITH Fidili_CTE1X ( FirstName,LastName,SubscribedDate, RegisteredDate, pers)
AS
(
SELECT 
FirstName,LastName,SubscribedDate, RegisteredDate,dbo.GetShDate(RegisteredDate) as pers
FROM ClubProfile CP 
WHERE CP.CardNumber IS NOT NULL
AND IsExpired =0
)

SELECT LastName,pers FROM Fidili_CTE1X
  CREATE TABLE #TEMPX
 (
      Lastname nvarchar(max) ,pers varchar(10)
 )
 Insert into #TEMPX 
 select * from Fidili_CTE1X
 ;WITH FIDILIO_CTE2Y(irstName,LastName,SubscribedDate, RegisteredDate,PERS)
 AS
 (
   SELECT 
FirstName,LastName,SubscribedDate, RegisteredDate,dbo.GetShDate(RegisteredDate) as pers
FROM ClubProfile CP 
WHERE CP.CardNumber IS NOT NULL
)


SELECT  LASTNAME,PERS FROM FIDILIO_CTE2Y

CREATE TABLE #TEMPY
(
Lastname nvarchar(max) ,pers varchar(10)
)
Insert into #TEMPY
select * from FIDILIO_CTE2Y

2 个答案:

答案 0 :(得分:1)

我认为你的误解是CTE不会选择任何数据。他们创造了一张桌子。您必须以与任何其他表相同的方式与该表进行交互。

但是,您的脚本比它需要的更复杂。这有什么问题?

SELECT FirstName,LastName,SubscribedDate, RegisteredDate,dbo.GetShDate(RegisteredDate) as pers
INTO #TEMPY
FROM ClubProfile CP 
WHERE CP.CardNumber IS NOT NULL

这与您的脚本具有相同的结果,但由于脚本中的错误,我无法确定您真正想要的列。

答案 1 :(得分:0)

使用此

use fidilio
;WITH Fidili_CTE1X ( FirstName,LastName,SubscribedDate, RegisteredDate, pers)
AS
(
SELECT 
FirstName,LastName,SubscribedDate, RegisteredDate,dbo.GetShDate(RegisteredDate) as pers
FROM ClubProfile CP 
WHERE CP.CardNumber IS NOT NULL
AND IsExpired =0
)

SELECT LastName,pers  into #TEMPX  FROM Fidili_CTE1X

 ;WITH FIDILIO_CTE2Y(irstName,LastName,SubscribedDate, RegisteredDate,PERS)
 AS
 (
   SELECT 
FirstName,LastName,SubscribedDate, RegisteredDate,dbo.GetShDate(RegisteredDate) as pers
FROM ClubProfile CP 
WHERE CP.CardNumber IS NOT NULL
)
SELECT  LASTNAME,PERS  into #TEMPY FROM FIDILIO_CTE2Y

select * from FIDILIO_CTE2Y