1 year ago

#384949

test-img

TonyTightTop

Alternative to Union for inserting data from three tables into one temp table

I am trying to insert data from three separate tables into one temp table. The three tables mostly consist of the same columns but there is no link between them (i.e. no link between tblOne and tblTwo in the example below). I am able to get the result I'm hoping for using the following code but I am thinking there must be a more efficient way that I am not using.

DECLARE @ExampleTable TABLE(Column1 INT, Column2 INT, Column3 INT, Column4 NVARCHAR(50), Column5 DATETIME, Column6 decimal(19,8))
INSERT INTO @ExampleTable
SELECT A.Column1, A.Column2, A.Column3, A.Column4, Aa.Column5, A.Column6
FROM    tblOne AS A INNER JOIN
            tblOneJoin AS Aa ON Aa.ID = A.ExampleColumn
WHERE   ClauseColumn IN (2,3)
UNION 
SELECT B.Column1, B.Column2, B.Column3, B.Column4, Bb.Column5, B.Column6
FROM    tblTwo AS B INNER JOIN
            tblTwoJoin AS Bb ON Bb.ID = B.ExampleColumn
WHERE   ClauseColumn IN (2,3)
UNION 
SELECT C.Column1, C.Column2, C.Column3, C.Column4, Cc.Column5, C.Column6
FROM    tblThree AS C INNER JOIN
            tblThreeJoin AS Cc ON Cc.ID = C.ExampleColumn
WHERE   ClauseColumn IN (2,3)

Am I right in thinking there is a better way to do this?

sql

sql-server

tsql

union

0 Answers

Your Answer

Accepted video resources