Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert into temp table without creating it from union results

I have the below query that get results from more than one select. Now I want these to be in a temp table.

Is there any way to insert these into a temp table without creating the table?

I know how to do that for select

Select * into #s --like that

However how to do that one more than one select?

SELECT  Ori.[GeoBoundaryAssId],  Ori.[FromGeoBoundaryId], Ori.Sort 
From [GeoBoundaryAss] As Ori where  Ori.[FromGeoBoundaryId] = (select distinct [FromGeoBoundaryId] from inserted )

Union 

SELECT  I.[GeoBoundaryAssId],  I.[FromGeoBoundaryId], I.Sort 
From [inserted] I ;
like image 649
mmssaann Avatar asked Jun 10 '13 04:06

mmssaann


2 Answers

Add INTO after the first SELECT.

SELECT  Ori.[GeoBoundaryAssId],  Ori.[FromGeoBoundaryId], Ori.Sort 
INTO #s
From [GeoBoundaryAss] As Ori where  Ori.[FromGeoBoundaryId] = (select distinct [FromGeoBoundaryId] from inserted )

Union 

SELECT  I.[GeoBoundaryAssId],  I.[FromGeoBoundaryId], I.Sort 
From [inserted] I ;
like image 80
Mikael Eriksson Avatar answered Sep 16 '22 12:09

Mikael Eriksson


Try this,

INSERT INTO #s ([GeoBoundaryAssId], [FromGeoBoundaryId], Sort)
(
    SELECT  Ori.[GeoBoundaryAssId],  Ori.[FromGeoBoundaryId], Ori.Sort 
    FROM [GeoBoundaryAss] AS Ori WHERE  Ori.[FromGeoBoundaryId] in (SELECT DISTINCT [FromGeoBoundaryId] FROM inserted )

    UNION 

    SELECT  I.[GeoBoundaryAssId],  I.[FromGeoBoundaryId], I.Sort 
    FROM [inserted] I 
)
like image 43
SaminatorM Avatar answered Sep 18 '22 12:09

SaminatorM