Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple select statements into a temp table

I am having three tables with different data and i need to insert into one TEMP table and return that table in StoredProcedure.

I tried as:

-- To get last 10 Days Letters count
SELECT col1,col2,1 AS Type, LettersCount
INTO #temp FROM tblData

-- To get last 4 weeks Letters count
SELECT col1,col2,2 AS Type, LettersCount
INTO #temp FROM tblData

-- To get month wise Letters count
SELECT col1,col2,3 AS Type, LettersCount
INTO #temp FROM tblData

Showing Error as

Msg 2714, Level 16, State 1, Line 16
There is already an object named '#temp ' in the database.
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near 'T'.
Msg 2714, Level 16, State 1, Line 32
There is already an object named '#temp ' in the database.
like image 311
Dinesh Reddy Alla Avatar asked Dec 12 '14 06:12

Dinesh Reddy Alla


People also ask

How do I insert multiple selections?

Under Insert controls, click Multiple-Selection List Box. If you cleared the Automatically create data source check box in step 3, select a repeating field in the Multiple-Selection List Box Binding dialog box to which you want to bind the multiple-selection list box.

Can you use 2 SELECT statements in SQL?

Put differently, UNION allows you to write two separate SELECT statements, and to have the results of one statement display in the same table as the results from the other statement. SQL has strict rules for appending data: Both tables must have the same number of columns.

Can we insert multiple values to a table at a time?

If you want to insert more rows than that, you should consider using multiple INSERT statements, BULK INSERT or a derived table. Note that this INSERT multiple rows syntax is only supported in SQL Server 2008 or later. To insert multiple rows returned from a SELECT statement, you use the INSERT INTO SELECT statement.


1 Answers

Create the temporary table once, then insert into it for the other two SELECT statements:

SELECT col1, col2, 1 AS Type, LettersCount
  INTO #temp
  FROM tblData;

INSERT INTO #temp
    SELECT col1, col2, 2 AS Type, LettersCount
      FROM tblData;

INSERT INTO #temp
    SELECT col1, col2, 3 AS Type, LettersCount
      FROM tblData;
like image 195
Jonathan Leffler Avatar answered Oct 05 '22 07:10

Jonathan Leffler