Matteo
Matteo

Reputation: 346

Insert into table linked by foreign key

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?

Upvotes: 1

Views: 67

Answers (2)

PSK
PSK

Reputation: 17943

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'

Upvotes: 2

SANM2009
SANM2009

Reputation: 1998

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.

Upvotes: 1

Related Questions