I'd like to merge two tables - SomeTable_1 and SomeTable_2. They have the same columns and come from different DBs (SomeDB_1/SomeDB_2).
So I'm starting with blank table (SomeTable) in another DB (SomeDB) and starting to merge data from above mentioned tables.
INSERT INTO [SomeDB].[dbo].[SomeTable] SELECT * FROM [SomeDB_1].[dbo].[SomeTable_1];
INSERT INTO [SomeDB].[dbo].[SomeTable] SELECT * FROM [SomeDB_2].[dbo].[SomeTable_2];
Everything works fine but table logic is based on ID (primary key) and when I merge two tables according to described above, I'm getting two duplicate records (with the same ID). Is there any way how to handle this issue? Thanks a lot in advance.
Tou can do this way :
Instead of using * you can set the the column name avoiding the id column ..
INSERT INTO [SomeDB].[dbo].[SomeTable] (column1, column2, column3...) SELECT column1, column2, column3 , ... FROM [SomeDB_1].[dbo].[SomeTable_1];
INSERT INTO [SomeDB].[dbo].[SomeTable] (column1, column2, column3...) SELECT column1, column2, column3 , ...FROM [SomeDB_2].[dbo].[SomeTable_2];
Be certain that you make the id column in SomeTable set to autoincrement.
Use can use the below code. It will allow to insert data to the IDENTITY COLUMN. This is working fine with SQL Server 2012
SET IDENTITY_INSERT [SomeDB].[dbo].[SomeTable] ON
INSERT INTO [SomeDB].[dbo].[SomeTable] SELECT * FROM [SomeDB_1].[dbo].[SomeTable_1];
INSERT INTO [SomeDB].[dbo].[SomeTable] SELECT * FROM [SomeDB_2].[dbo].[SomeTable_2];
SET IDENTITY_INSERT [SomeDB].[dbo].[SomeTable] OFF
Related
I'm creating a C# Winforms application for recipe management in an industrial environment.
I created a SQL Server table with 130 columns. The table contains a column called CheckData (of datatype Timestamp), which I use to detect changes made to a row.
If I insert a new row to that table all works fine. The code I use is:
INSERT INTO tablename (Column1, column2, column3, column4)
VALUES (value1, value2, value3, value4)
I just assign values to major columns, the others get their default value. I do not assign a value to the timestamp field since it's written by the system.
Additionally, I want to copy a row from this table to the same table (duplicate a data record).
I copy the source row to a temporary table, drop the ID (primary key) and the timestamp fields in that temporary table and try to insert that only row in the temporary table into the table. This fails.
Here's the code:
SELECT *
INTO #temptable
FROM tablename
WHERE Recipe_No = 8;
ALTER TABLE #temptable DROP COLUMN ID, CHECKDATA;
ALTER TABLE #temptable REBUILD;
UPDATE #temptable
SET Recipe_No = 9, Recipe_Name = 'Test'
WHERE Recipe_No = 8;
INSERT INTO tablename
SELECT * FROM #temptable;
I don't understand where the difference is between inserting a new row thru INSERT INTO xxx (yyy) VALUES (zzz) and INSERT INTO xxx SELECT * FROM yyy. In both cases I don't try to write the timestamp value in the new row.
Does anybody have an idea what I'm missing here?
I don't understand where the difference is between inserting a new row thru INSERT INTO xxx (yyy) VALUES (zzz) and INSERT INTO xxx SELECT * FROM yyy.
With this,
INSERT INTO xxx SELECT * FROM yyy.
you are failing to specify the column mappings from the SELECT to the target table. You should always use
INSERT INTO xxx (Column1, Column2, . . .)
SELECT (Column1, Column2, . . .)
FROM yyy
Here's a simplified example of what you're attempting:
drop table if exists t
create table t(id int, a int)
insert into t(id,a) values (1,1)
select * into #t from t where id = 1
alter table #t drop column id
insert into t select * from #t
and it will fail with
Msg 213, Level 16, State 1, Line 12
Column name or number of supplied values does not match table definition.
because the temp table doesn't even have the same number of columns. And even if it did, you wouldn't know for sure that the column mappings were correct.
It is failing because essentially your command
INSERT INTO tablename SELECT * FROM #temptable;";
Is telling SQL - "Insert everything into this table from this temp table."
While you can work around this, I would say why don't you just try inserting into only the columns made available in your current table with only the values you would like to include. Instead of needing to drop the columns/values, you just don't import it to begin with.
An alternative - if you can write to a helper table, it may be beneficial to INSERT INTO that helper table, as opposed to a temp table, the values you have. Then transform that helper table, and THEN you can do INSERT INTO final_table SELECT * FROM helper. This should give you the results you're looking for.
I hope this is helpful, and I hope it explains why your current command is failing.
I've got 2 tables:
TravelRequest
TravelReqID(PK)
PlanningTypeCode(FK)
Days
Hours
Mail
PlanningType
PlanningTypeCode(PK)
PlanningType
I want to insert some records into TravelRequest but I need to show also PlanningType.PlanningType.
I tried this query
INSERT INTO [Travel].[TravelRequest]([PlanningType].PlanningType,Days,Hours,Mail)
VALUES('Start Training',10,1,1)
But SQL Server shows me this error:
Invalid column name 'PlanningType'.
How can I insert PlanningType value?
Your INSERT statement is not correct.
Insert syntax is like following.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Where all the columns should be from the table where you are trying to insert the data.
You should be writing your query like following. [Assuming that TravelReqID is Identity column)
INSERT INTO TravelRequest(PlanningTypeCode,Days,Hours,Mail)
SELECT PT.PlanningTypeCode,10,1,1
FROM [PlanningType] PT
WHERE PT.PlanningType='Start Training'
You are trying to write to two table without creating a link between the two in your query.
You need to create a join before you can write a query like that.
I'm using SQL Server 2012 to try to take the values of one column in a table and put them into the values of another column table in another. If I try to run the following query:
INSERT INTO table2 (column3)
SELECT column3
FROM table1
WHERE (ScopeID IS NOT NULL)
ORDER BY Name
For table2, column3 is the same type (an int), NULL values are allowed. But when I try to execute the query, it returns:
Cannot insert the value NULL into column 'column1', table 'dbo.table2';, column does not allow nulls. INSERT fails.
But I'm not trying to insert into column1... Is it just a syntax thing where the order of the columns HAVE to match?
You are inserting into column1. Remember, you are inserting entire rows of values, so you should really have a value for all columns. Your query is equivalent to:
INSERT INTO table2 (column1, column2, column3)
SELECT NULL, NULL, column3
FROM table1
WHERE (ScopeID IS NOT NULL)
ORDER BY Name;
(and so on for all the columns in the table.)
I am guessing that you actually want an update, but your question doesn't provide enough information to give further guidance.
I have a table with an identity column in a server and have a other table with same structure in another server.. Now I want to copy all data from one table to other table but I can't help it...
I have already created a linked server..
I use this:
insert into [server].[database].[dbo].[table1]
select *
from table2
I also use this query without identity column in the place of *
insert into [server].[database].[dbo].[table1]
select column1, column2
from table2
What should I do ?
If you want to insert into a second table that also has an identity column, then you need to explicitly define the list of columns you're inserting into and omit the identity column:
insert into [server].[database].[dbo].[table1] (col1, col2)
select column1, column2
from table2
This way, SQL Server can insert the identity values in the target table as it should
Update:
two scenarios:
(1) you want to insert the existing values from the identity column from the old table into the new one - in that case, you need to use SET IDENTITY_INSERT ON/OFF in your query:
SET IDENTITY_INSERT [192.168.1.6].[audit].[dbo].[tmpDTTransfer] ON
INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (id, code, transfer1)
SELECT
id, code, transfer1
FROM
tmpDTTransfer
SET IDENTITY_INSERT [192.168.1.6].[audit].[dbo].[tmpDTTransfer] OFF
(2) if you don't want to insert the existing identity values, but just the other columns and let SQL Server assign new identity values in the target table, then you don't need to use SET IDENTITY_INSERT ON/OFF in your query:
INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (code, transfer1)
SELECT
code, transfer1
FROM
tmpDTTransfer
But in any you, you should always explicitly define the list of columns to insert into, in your target table.
DO NOT USE:
INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer]
.......
But instead use
INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (Code, Transfer1)
.......
or
INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (Id, Code, Transfer1)
.......
or whatever you need. Be explicit about what you want to insert into!
Set IDENTITY_INSERT for table:
SET IDENTITY_INSERT [server].[database].[dbo].[table1] ON
insert into [server].[database].[dbo].[table1]
select column1,column2
from table2
SET IDENTITY_INSERT [server].[database].[dbo].[table1] OFF
If you don't need to necessarily use SQL script, than you can do it using SQL Server Import and Export Wizard.
You can read the tutorial here on MSDN.
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