Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a temp table from a "with table as" CTE expression

I cannot seem to access a temp table based on the results of a CTE expression.

how do you create a temp table, and access the temp declared within a CTE.

in the example below, the last line will throw an error.

Thanks

 DECLARE @tbl TABLE
  ( 
   Id int
  ,ParentId int
  )
INSERT  INTO @tbl
        ( Id, ParentId )
select t_package.package_id, t_package.parent_ID from t_package 
;
WITH  abcd
        AS (
              -- anchor
            SELECT   id
                    ,ParentID
                    ,CAST(id AS VARCHAR(100)) AS [Path]
                    ,0 as depth
            FROM    @tbl
            WHERE   ParentId = 0
            UNION ALL
              --recursive member
            SELECT  t.id
                   ,t.ParentID
                   ,CAST(a.[Path] + ',' + CAST( t.ID AS VARCHAR(100)) AS varchar(100)) AS [Path]
                   ,a.depth +1
            FROM    @tbl AS t
                    JOIN abcd AS a ON t.ParentId = a.id
           )
SELECT * from abcd;

insert into #TMP (id,parent,branch,depth) (select * from abcd)
like image 415
Hightower Avatar asked Nov 01 '25 08:11

Hightower


1 Answers

A set of CTEs introduced by a WITH clause is valid for the single statement that follows the last CTE definition. Here, it seems you should just skip the bare SELECT and make the INSERT the following statement:

WITH  abcd
        AS (
              -- anchor
            SELECT   id
                    ,ParentID
                    ,CAST(id AS VARCHAR(100)) AS [Path]
                    ,0 as depth
            FROM    @tbl
            WHERE   ParentId = 0
            UNION ALL
              --recursive member
            SELECT  t.id
                   ,t.ParentID
                   ,CAST(a.[Path] + ',' + CAST( t.ID AS VARCHAR(100)) AS varchar(100)) AS [Path]
                   ,a.depth +1
            FROM    @tbl AS t
                    JOIN abcd AS a ON t.ParentId = a.id
           )
insert into #TMP (id,parent,branch,depth) select * from abcd

select * from #TMP

(I've added the select from #TMP so that we still get a result set returned to the client, albeit that the insert and select statements are now reversed).

like image 59
Damien_The_Unbeliever Avatar answered Nov 03 '25 22:11

Damien_The_Unbeliever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!