Search code examples
sqlsql-server-2012temp-tables

insert into temp table using Cross Apply?


I want to create a temp table and insert values based on the select. The query doesn't execute, What am i missing ? I eventually want to loop thru the temp table

Create Table #temp (ID varchar(25),Source_Id varchar(25),Processed   varchar(25), Status varchar(25),Time_Interval_Min varchar(25))
Insert into #temp   
Select t.*
From
   (SELECT DISTINCT source_id 
    FROM Activity_WorkLoad) t1
    CROSS APPLY 
   (
    SELECT TOP 1
      aw.ID,
      Source_Id 
      ,Processed 
      ,Status 
      ,Time_Interval_Min
   FROM [dbSDS].[dbo].[Activity_WorkLoad] aw
   JOIN [dbSDS].[dbo].[SDA_Schedule_Time] st ON aw.SDA_Resource_ID = st.ID
   WHERE aw.Source_Id = t1.Source_Id AND aw.Status = 'Queued'
   ORDER BY Processed DESC  
   )t

Solution

  • When you cross apply, you still need an alias:

    Insert into #temp   (id, source_id, processed, status, time_interval_min)
        Select tt.*
        From (SELECT DISTINCT source_id 
              FROM Activity_WorkLoad
             ) t CROSS APPLY 
             (SELECT TOP 1 aw.ID, Source_Id, Processed, Status, Time_Interval_Min
              FROM [dbSDS].[dbo].[Activity_WorkLoad] aw JOIN 
                   [dbSDS].[dbo].[SDA_Schedule_Time] st
                   ON aw.SDA_Resource_ID = st.ID
              WHERE aw.Source_Id = t.Source_Id AND aw.Status = 'Queued'
              ORDER BY Processed DESC  
            ) tt;
    

    I also assume that you want results from the second subquery, not the first, because the first does not have enough columns.