Insert into a Temp Table in a CTE

♀尐吖头ヾ 提交于 2019-12-11 19:28:12

问题


I am trying to insert data into a temp table within a CTE. Here is the Code I am using: Can someone provide a little guidance on why it is not working.

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)

Thanks, Scott


回答1:


Simply, you cannot use the INSERT function inside a CTE. Assuming "Final" was one of the other CTE's in the multi CTE script, just move the INSERT INTO #Clients outside the CTE script. You seemingly don't need the temp table, since you are using CTE's, the Clients CTE will be available temp table or no. I suggest getting rid of the temp table altogether and continuing with the CTE method you already have in place. You may need to post more of the script to get better scope of the question.

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



回答2:


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



回答3:


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 


来源:https://stackoverflow.com/questions/23158917/insert-into-a-temp-table-in-a-cte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!