Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using SELECT INTO with multiple rows

Tags:

sql

insert

This is re I want to create a table using the results of a query by utilizing SELECT INTO. The syntax

SELECT *
INTO Persons_Backup
FROM Persons

is very close to what I want to achieve, with the difference being that I want the FROM to use a query as source.

My situation is a bit more complicated than these simple examples.

I need to create a table and insert multiple rows at the same time. If I could (I can't) use a previously created table the statement would look like this:

INSERT INTO Person_Backup12 (Col1, Col2, Col3)
Select 1, 'a','2001-01-01 12:00'
UNION ALL
Select 83, 'z','2011-09-30 13:27'
UNION ALL
Select 777, 'k','1997-04-25 09:27'

Can I do that while creating a table at the same time?

like image 817
callisto Avatar asked Apr 06 '11 12:04

callisto


People also ask

Is it possible to have multiple rows with select from dual?

No. dual has just one row, but you can use union all : This is just one way to generate a table "on-the-fly" in Oracle.

Can you insert into multiple rows?

Yes, instead of inserting each row in a separate INSERT statement, you can actually insert multiple rows in a single statement. To do this, you can list the values for each row separated by commas, following the VALUES clause of the statement.

Is select into faster than insert into?

INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.

How do I select multiple rows in a table?

Select multiple items in a table or list using shift-click and ctrl-click. This can be useful to add multiple resources to a graph or modify multiple items at a time. To select a range of items, hold down the shift key and then click on the top item followed by the bottom item.


2 Answers

You can put your query into a common table expression or derived table then SELECT ... INTO from that.

;WITH cte (Col1, Col2, Col3) AS
(
Select 1, 'a','2001-01-01 12:00'
UNION ALL
Select 83, 'z','2011-09-30 13:27'
UNION ALL
Select 777, 'k','1997-04-25 09:27'
)
SELECT *
INTO NewTable
FROM cte

In this case you would probably need some explicit casts to get the desired column datatype (datetime rather than char etc.)

like image 117
Martin Smith Avatar answered Oct 29 '22 08:10

Martin Smith


A CTE shouldn't be necessary:

Select 1 as 'Col1', 'a' as 'Col2','2001-01-01 12:00' as 'Col3'
INTO Person_Backup12
UNION ALL
Select 83, 'z','2011-09-30 13:27'
UNION ALL
Select 777, 'k','1997-04-25 09:27'

Worked fine for me in 2008 r2.

like image 44
JNK Avatar answered Oct 29 '22 08:10

JNK