SQL Insert from other table with Same Schema - sql

Table1 and Table2 have same schema, same columns and same types, and Table2 is empty while Table1 has some data
Insert into Table2 values(Select * from Table1)
how to transfer the data with sql statement? i think syntax is valid in oracle, but how to do with sql-server

You can leave out the values statement:
insert into table2
select * from table1
That said, you should really be in the habit of listing column names, both for the insert and select in this case. The columns could have the same name and type -- but be in different order.

You might possibly want to drop table 2 and then do a select * into table2 from table1. This way you are guaranteed to have the same structure. Because when somebody changes the structure of either table, but not the other, insert into will bomb.

Related

Select from inherited table

I have this inheritance in my database and I need to use a SELECT query and INSERT query to it.
I can't seem to pull this off.
It's about the Item and it's inheritances.
This could be helpful?
INSERT INTO table2
SELECT *
FROM table1
WHERE condition;
I don't know if i've understood your question but, you want to insert some values into a table selecting from an another table.

Save return values from INSERT...RETURNING into temp table (PostgreSQL)

I have a table table1 with columns id,value1 and value2.
Also I have a query
INSERT INTO table1(value1,value2) SELECT value3,value4 FROM table2 RETURNING id
that returns set of ids.
I want to store return values (these ids) in some temp table. Something like that:
INSERT INTO TEMP temp1 INSERT INTO table1(value1,value2) SELECT value3,value4 FROM table2 RETURNING id
How can I do it?
DBMS is PostgreSQL
with inserted as (
INSERT INTO table1 (value1,value2)
SELECT value3,value4
FROM table2
RETURNING id
)
insert into temp
select id
from inserted;
This requires Postgres 9.2 or later.
Two options.
If you need it just for one follow-up query, a with statement (see the horse's answer) is the easiest.
If you need it for more than one follow-up query, the other option is to not use insert ... returning, but rather create table as:
CREATE TEMPORARY TABLE foo AS
SELECT value3,value4 FROM table2
Caveats: if necessary, create the indexes you need on the table -- and analyze it if you do.

Difference between Select Into and Insert Into from old table?

What is difference between these in terms of constraints *keys* etc.
Select Into Statement
SELECT column1, column2, someInt, someVarChar
INTO ItemBack1
FROM table2
WHERE table2.ID = 7
Insert Into Statement
INSERT INTO table1 ( column1, column2, someInt, someVarChar )
SELECT table2.column1, table2.column2,
FROM table2
WHERE table2.ID = 7
and also
Create table ramm as select * from rammayan
Edit 1:
Database SQL Server 2008
I'm going to assume MySQL here.
The first two are identical, as the documentation states.
The third statement allows for both table creation and population, though your syntax is wrong up there; look at the right syntax for more info.
Update
It's SQL Server =p
SELECT column1, column2, someInt, someVarChar
INTO ItemBack1
FROM table2
WHERE table2.ID = 7
The first statement will automatically create the ItemBack1 table, based on table2.
INSERT INTO table1 ( column1, column2, someInt, someVarChar )
SELECT table2.column1, table2.column2,
FROM table2
WHERE table2.ID = 7
The second second statement requires that table1 already exists.
See also: http://blog.sqlauthority.com/2007/08/15/sql-server-insert-data-from-one-table-to-another-table-insert-into-select-select-into-table/
If there's any difference in constraints, it would be because the second statement depends on what you have already created (and if the table is populated, etc.).
Btw, the third statement is Oracle(tm) and is the same as the first statement.
There are some very important differences between SELECT INTO and INSERT.
First, for the INSERT you need to pre-define the destination table. SELECT INTO creates the table as part of the statement.
Second, as a result of the first condition, you can get type conversion errors on the load into the table using INSERT. This cannot happen with a SELECT INTO (although the underlying query could produce an error).
Third, with a SELECT INTO you need to give all your columns names. With an INSERT, you do not need to give them names.
Fourth, SELECT INTO locks some of the metadata during the processing. This means that other queries on the database may be locked out of accessing tables. For instance, you cannot run two SELECT INTO statements at the same time on the same database, because of this locking.
Fifth, on a very large insert, you can sometimes see progress with INSERT but not with SELECT INTO. At least, this is my experience.
When I have a complicated query and I want to put the data into a table, I often use:
SELECT top 0 *
INTO <table>
FROM <query>
INSERT INTO <table>
SELECT * FROM <query>
Select Into ->Creates the table on the fly upon select execution
while
Insert Into ->Presumes that the Table DB already exist
lastly
Create, simply creates the table from the return result of the query
I don't really understand your question. Let's try:
The 1st one selects the value of the columns "someVarChar" into a variable called "ItemBack1". Depending on your SQL-Server (mysql/oracle/mssql/etc.) you can now do some logic with this var.
The 2nd one inserts the result of
SELECT table2.column1, table2.column2, 8, 'some string etc.'
FROM table2
WHERE table2.ID = 7
into the table1 (Copy)
And the 3rd creates a new table "ramm" as a copy of the table "rammayan"
Generally speaking
Each one has its own particularities, one creates a temporary table, other uses a previously existing table and the third one creates a new table with exact same estructure and formatting
SELECT…INTO creates a new table in the default filegroup and inserts the resulting rows from the query into it
INSERT INTO: fills an already existing table
INSERT...INTO
The third option is known as CTAS (Create Table As Select) do a search and you will get tons of usefull links. Basically it creates a table, not a temporary one, with the structure and types used on the SELECT statement.
I wanted to add some more links but as I'm a new user I'm only allowed to post 2 links to prevent spam.
INSERT INTO SELECT inserts into an existing table.
SELECT INTO creates a new table and puts the data in it.
All of the columns in the query must be named so each of the columns in the table will have a name. This is the most common mistake I see for this command.
The data type and nullability come from the source query.
If one of the source columns is an identity column and meets certain conditions (no JOINs in the query for example) then the column in the new table will also be an identity.
INSERT INTO SELECT
CREATE TABLE ExistingTableName1 (ColumnName VARCHAR(255));
GO
INSERT
INTO ExistingTableName1
SELECT ColumnaName
FROM ExistingTableName2;
GO
SELECT INTO INSERT
SELECT ColumnName INTO NewTableName
FROM ExistingTableName1;
GO
The SQL SELECT INTO Statement
The SELECT INTO statement copies data from one table into a new table.
SELECT INTO Syntax
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
The new table will be created with the column-names and types as defined in the old table. You can create new column names using the AS clause.
The SQL INSERT INTO SELECT Statement
The INSERT INTO SELECT statement copies data from one table and inserts it into another table.
INSERT INTO SELECT Syntax
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
INSERT INTO SELECT requires that data types in source and target tables match
The existing records in the target table are unaffected

SQL insert into using Union should add only distinct values

So I have this temp table that has structure like:
col1 col2 col3 col3
intID1 intID2 intID3 bitAdd
I am doing a union of the values of this temp table with a select query and storing
it into the same temp table.The thing is col3 is not part of the union query I will
need it later on to update the table.
So I am doing like so:
Insert into #temptable
(
intID1,
intID2,
intID3
)
select intID1,intID2,intID3
From
#temptable
UNION
select intID1,intID2,intID3
From
Table A
Issue is that I want only the rows that are not already existing in the temp table to be added.Doing it this way will add a duplicate of the already existing row(since union will return one row)How do I insert only those rows not existing in the current temp table in my union query?
Use MERGE:
MERGE INTO #temptable tmp
USING (select intID1,intID2,intID3 From Table A) t
ON (tmp.intID1 = t.intID1 and tmp.intID2 = t.intID2 and tmp.intID3 = t.intID3)
WHEN NOT MATCHED THEN
INSERT (intID1,intID2,intID3)
VALUES (t.intID1,t.intID2,t.intID3)
Nice and simple with EXCEPT
INSERT INTO #temptable (intID1, intID2, intID3)
SELECT intID1,intID2,intID3 FROM TableA
EXCEPT
SELECT intID1,intID2,intID3 FROM #temptable
I see where you are coming from. In most programming languages #temptable would be a variable (a relation variable or relvar for short) to which you would assign a value (a relation value) thus:
#temptable := #temptable UNION A
In the relational model, this would achieve the desired result because a relation has no duplicate rows by definition.
However, SQL is not truly relational and does not support assignment. Instead, you are required to add rows to a table using SQL DML INSERT statements (which is not so bad: the users of a truly relational database language, if we had one, would no doubt demand a similar shorthand for relational assignment!) but you are also required to do the test for duplicates yourself.
The answers from Daniel Hilgarth and Joachim Isaksson both look good. It's good practice to have two good, logically sound candidate answers then look for criteria (usually performance under typical load) to eliminate one (but retaining it commented out for future re-testing!)

SQL Server Generate Script To Fill Tables With Data From Other Database?

Let's say I have two databases with identical tables, but one database's tables contains data while the other doesn't. Is there a way in SQL Server to generate a script to fill the empty tables with data from the full tables?
If the tables are identical and don't use an IDENTITY column, it is quite easy.
You would do something like this:
INSERT INTO TableB
SELECT * FROM TableA
Again, only for identical table structures, otherwise you have to change the SELECT * to the correct columns and perform any conversions that are necessary.
And, to add to the #WilliamD answer, if there is an IDENTITY column you can use a variation of the INSERT statement.
Assuming you have two columns (Col1 and Col2, with Col1 having IDENTITY property) in the tables, you can do the following:
SET IDENTITY_INSERT TableB ON
INSERT INTO TableB (col1, col2)
SELECT col1, col2 FROM TableA
SET IDENTITY_INSERT TableB OFF
It's necessary to list the columns in this situation.