Insert into table linked by foreign key - sql

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.

Related

SQL Server Insert Into Table containing a column "Timestamp (Rowversion)"

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.

SQL Server : INSERT INTO SELECT doesn't insert into the correct column

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.

Increment ID number in case of merging tables (SQL)

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

Insert result set from UNPIVOT into table

I am trying to find the syntax for inserting the results from an UNPIVOT statement into an existing table in the database?
simplest answer which works for any SELECT including UNPIVOT would be...
INSERT INTO MyTable
SELECT statement
However, this does require that your destination tables columns match your SELECT statement columns.
Although you can get around this limitation with...
INSERT INTO MyTable (column1, column2....)
SELECT statement

large insert in two tables. First table will feed second table with its generated Id

One question about how to t-sql program the following query:
Table 1
I insert 400.000 mobilephonenumbers in a table with two columns. The number to insert and identity id.
Table 2
The second table is called SendList. It is a list with 3columns, a identity id, a List id, and a phonenumberid.
Table 3
Is called ListInfo and contains PK list id. and info about the list.
My question is how should I using T-sql:
Insert large list with phonenumbers to table 1, insert the generated id from the insert of phonenum. in table1, to table 2. AND in a optimized way. It cant take long time, that is my problem.
Greatly appreciated if someone could guide me on this one.
Thanks
Sebastian
What version of SQL Server are you using? If you are using 2008 you can use the OUTPUT clause to insert multiple records and output all the identity records to a table variable. Then you can use this to insert to the child tables.
DECLARE #MyTableVar table(MyID int);
INSERT MyTabLe (field1, field2)
OUTPUT INSERTED.MyID
INTO #MyTableVar
select Field1, Field2 from MyOtherTable where field3 = 'test'
--Display the result set of the table variable.
Insert MyChildTable (myID,field1, field2)
Select MyID, test, getdate() from #MyTableVar
I've not tried this directly with a bulk insert, but you could always bulkinsert to a staging table and then use the processs, described above. Inserting groups of records is much much faster than one at a time.