Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a foreign key using a Sub-SELECT in SQL Server

I've just started working with SQL Server for the first time and I'm having trouble populating test data. I have two tables where one has a foreign key to the other and I would like to be able to insert a new record using the following SQL:

insert into Employee (
    EmployeeName,
    DepartmentId
) values (
    "John Doe",
    (select Id from Department where DepartmentName = 'Accounting')
);

This statement works fine in Oracle but in SQL Server I get an error saying:

Subqueries are not allowed in this context.

Does anybody know the right way to do this in SQL Server?

like image 936
KevinS Avatar asked Sep 29 '09 15:09

KevinS


1 Answers

INSERT INTO Employee 
    (EmployeeName, DepartmentId)
SELECT 
    'John Doe' AS EmployeeName, Id AS DepartmentId
FROM 
    Department WHERE DepartmentName = 'Accounting';
like image 88
Mitch Wheat Avatar answered Oct 22 '22 02:10

Mitch Wheat