copy the tables after execution - sql

I would like to create new table after executing that query
create table newTable as select * from oldTable
However, this does not appear to work. How do I get the new table after executing some queries?

The syntax in general is like:
CREATE TABLE new_table
AS (SELECT * FROM old_table);
For example:
CREATE TABLE suppliers
AS (SELECT id, address, city, state, zip
FROM companies
WHERE id > 1000);
Try removing the stars (*) and add the brackets.
Read here for more examples.

I am not sure what DBMS you are using or what errors you are getting, so I will try to answer for multiple systems.
If you are working with Oracle or PostgreSQL (there might be some other systems that this rule applies to), your syntax seems to be correct. Just make sure your new table doesn't exist yet - otherwise it's going to error out. In case if you are trying to insert into an existing table - which I don't think the case is, however - you can try something like -
INSERT INTO newTable SELECT * FROM oldTable
On the other hand, if you are working with T-SQL (SQL Server), you could SELECT INTO the new table. The new table will be created with the old table's schema.
You can read more about the INTO Clause at MSDN Library.
Your code should look like -
SELECT *
INTO newTable
FROM oldTable
And, specifying the column names and filters also works the similar way -
SELECT Column1, Column2, Column3, ...
INTO newTable
FROM oldTable
WHERE <Filter Condition>
Whatever the case is, you would get more help if you specify the details.

As You Said you want to copy the values into new table after execution
whether if you are running the stored procedure using cursor let the cursor shuld be closed then use query as follows
Select * into Table1 from Table2
if you want to copy selected colums go for
Select Coloumn1 ,column2,... into table1 from table 2 where ............

Related

How do I copy data from one table to another in postgres using copy command

We use copy command to copy data of one table to a file outside database.
Is it possible to copy data of one table to another table using command.
If yes can anyone please share the query.
Or is there any better approach like we can use pg_dump or something like that.
You cannot easily do that, but there's also no need to do so.
CREATE TABLE mycopy AS
SELECT * FROM mytable;
or
CREATE TABLE mycopy (LIKE mytable INCLUDING ALL);
INSERT INTO mycopy
SELECT * FROM mytable;
If you need to select only some columns or reorder them, you can do this:
INSERT INTO mycopy(colA, colB)
SELECT col1, col2 FROM mytable;
You can also do a selective pg_dump and restore of just the target table.
If the columns are the same (names and datatypes) in both tables then you can use the following
INSERT INTO receivingtable (SELECT * FROM sourcetable WHERE column1='parameter' AND column2='anotherparameter');
Suppose there is already a table and you want to copy all records from this table to another table which is not currently present in the database then following query will do this task for you:
SELECT * into public."NewTable" FROM public."ExistingTable";

How to import data from one table to another table in sql

I have two database there is two table both databse
how to import data from database table to another database table in sql2008 standard edition. I have tried to export/import function but no luck .
would you Please help me ?
I think the code below will work for your case:
INSERT INTO table1 (column1,column2)
SELECT oldcolumn1, oldcolumn2
FROM table2
Optionally you could add a where clause.
Use this code and check below links
The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "*" though:
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
-- optionally WHERE ...
The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.
You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists.
OR Check this link
i hope this answer useful for you.

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

"select * into table" Will it work for inserting data into existing table

I am trying to insert data from one of my existing table into another existing table.
Is it possible to insert data into any existing table using select * into query.
I think it can be done using union but in that case i need to record all data of my existing table into temporary table, then drop that table and finally than apply union to insert all records into same table
eg.
select * into #tblExisting from tblExisting
drop table tblExisting
select * into tblExisting from #tblExisting union tblActualData
Here tblExisting is the table where I actually want to store all data
tblActualData is the table from where data is to be appended to tblExisting.
Is it right method.
Do we have some other alternative ?
You should try
INSERT INTO ExistingTable (Columns,..)
SELECT Columns,...
FROM OtherTable
Have a look at INSERT
and SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
No, you cannot use SELECT INTO to insert data into an existing table.
The documentation makes this very clear:
SELECT…INTO creates a new table in the default filegroup and inserts the resulting rows from the query into it.
You generally want to avoid using SELECT INTO in production because it gives you very little control over how the table is created, and can lead to all sorts of nasty locking and other performance problems. You should create schemas explicitly and use INSERT - even for temporary tables.
#Ryan Chase
Can you do this by selecting all columns using *?
Yes!
INSERT INTO yourtable2
SELECT * FROM yourtable1
Update from CTE? http://www.sqlservercentral.com/Forums/Topic629743-338-1.aspx

Copy Data from a table in one Database to another separate database

Basically I have a two databases on SQL Server 2005.
I want to take the table data from one database and copy it to another database's table.
I tried this:
SELECT * INTO dbo.DB1.TempTable FROM dbo.DB2.TempTable
This didn't work.
I don't want to use a restore to avoid data loss...
Any ideas?
SELECT ... INTO creates a new table. You'll need to use INSERT. Also, you have the database and owner names reversed.
INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable
SELECT * INTO requires that the destination table not exist.
Try this.
INSERT INTO db1.dbo.TempTable
(List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable
It's db1.dbo.TempTable and db2.dbo.TempTable
The four-part naming scheme goes:
ServerName.DatabaseName.Schema.Object
Hard to say without any idea what you mean by "it didn't work." There are a whole lot of things that can go wrong and any advice we give in troubleshooting one of those paths may lead you further and further from finding a solution, which may be really simple.
Here's a something I would look for though,
Identity Insert must be on on the table you are importing into if that table contains an identity field and you are manually supplying it. Identity Insert can also only be enabled for 1 table at a time in a database, so you must remember to enable it for the table, then disable it immediately after you are done importing.
Also, try listing out all your fields
INSERT INTO db1.user.MyTable (Col1, Col2, Col3)
SELECT Col1, COl2, Col3 FROM db2.user.MyTable
We can three part naming like database_name..object_name
The below query will create the table into our database(with out constraints)
SELECT *
INTO DestinationDB..MyDestinationTable
FROM SourceDB..MySourceTable
Alternatively you could:
INSERT INTO DestinationDB..MyDestinationTable
SELECT * FROM SourceDB..MySourceTable
If your destination table exists and is empty.
Don't forget to insert SET IDENTITY_INSERT MobileApplication1 ON to the top, else you will get an error. This is for SQL Server
SET IDENTITY_INSERT MOB.MobileApplication1 ON
INSERT INTO [SERVER1].DB.MOB.MobileApplication1 m
(m.MobileApplicationDetailId,
m.MobilePlatformId)
SELECT ma.MobileApplicationId,
ma.MobilePlatformId
FROM [SERVER2].DB.MOB.MobileApplication2 ma
Im prefer this one.
INSERT INTO 'DB_NAME'
(SELECT * from 'DB_NAME#DB_LINK')
MINUS
(SELECT * FROM 'DB_NAME');
Which means will insert whatsoever that not included on DB_NAME but included at DB_NAME#DB_LINK. Hope this help.
INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable
If we use this query it will return Primary key error.... So better to choose which columns need to be moved, like
INSERT INTO db1.dbo.TempTable // (List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable
Try this
INSERT INTO dbo.DB1.TempTable
(COLUMNS)
SELECT COLUMNS_IN_SAME_ORDER FROM dbo.DB2.TempTable
This will only fail if an item in dbo.DB2.TempTable is in already in dbo.DB1.TempTable.
This works successfully.
INSERT INTO DestinationDB.dbo.DestinationTable (col1,col1)
SELECT Src-col1,Src-col2 FROM SourceDB.dbo.SourceTable
You can copy one table to other db table even with some additional columns.
insert into [SchoolDb1].[dbo].Student(Col1, Col2,Col3, CreationTime, IsDeleted)
select Col1, Col2,Col3,,getdate(),0 from [SchoolDb2].[dbo].Student
These are additional columns: (CreationTime is datatime and IsDeleted is boolean)
select * from DBA1.TABLENAMEA;
create table TABLENAMEA as (select * from DBA1.TABLENAMEA);
These manual way provides more flexibility, but at the same time, works for table whose size is smaller to few thousands.
Do select * from <table name> from DB, once whole table is displayed, scroll till it's bottom.
Right click and do Export table as Insert statement, provide the name of the destination table and export the table as .sql file.
Use any text editor to further do regular find and replace operation to include more column names etc.
Use the INSERT statement in destination DB.