插入CTE中的临时表

时间:2014-04-18 17:19:57

标签: sql-server-2008 common-table-expression temp-tables

我正在尝试将数据插入到CTE中的临时表中。这是我正在使用的代码:有人可以提供一些关于它无法正常工作的指导。

Create Table #Clients
(HospMastID smallint    Null
,HospCode   smallint    Null
,ClientID   smallint    Null
,ControlGroup   smallint Null);

,Clients
as
    (Insert Into #Clients
    Select 
    Distinct
    HospMastID
    ,HospCode
    ,ClientID
    From
    Final)

谢谢, 斯科特

3 个答案:

答案 0 :(得分:0)

Create Table #Clients1
(standardid int Null
,fullnumber Varchar(200) Null
,description Varchar(1000) Null);

WITH standard_cte AS ( 
SELECT standardid, fullnumber, 
description FROM standard WHERE standardid = 1370 
UNION ALL 
SELECT s.standardid, s.fullnumber, s.description FROM standard s 
INNER JOIN standard_cte ON standard_cte.standardid = s.parentid ) 

Insert Into #Clients1(standardid ,fullnumber, description )
SELECT tempTable.standardid, fullnumber, description
FROM ( SELECT standardid, fullnumber, CONVERT(VARCHAR(MAX), description) as description FROM standard_cte WHERE standardid <> 1370 ) tempTable 

GROUP BY tempTable.StandardID, fullnumber, description

select * from #Clients1

drop table #Clients1

答案 1 :(得分:0)

简单地说,您不能在CTE中使用INSERT功能。假设“Final”是多CTE脚本中的其他CTE之一,只需将INSERT INTO #Clients移到CTE脚本之外即可。你似乎不需要临时表,因为你正在使用CTE,客户端CTE将是可用的临时表或否。我建议完全摆脱临时表并继续使用已有的CTE方法。您可能需要发布更多的脚本以获得更好的问题范围。

 ,Clients as
     (Select 
     Distinct
     HospMastID
     ,HospCode
     ,ClientID
     From
    Final)

答案 2 :(得分:0)

CREATE TABLE #Clients (
      HospMastID    SMALLINT    NULL
    , HospCode      SMALLINT    NULL
    , ClientID      SMALLINT    NULL
    , ControlGroup  SMALLINT    NULL
)

WITH Clients (HospMastID, HospCode, ClientID)
AS
(
    SELECT DISTINCT HospMastID, HospCode, ClientID
    FROM Final
)
INSERT INTO #Clients
SELECT HospMastID, HospCode, ClientID
FROM Clients