views:

273

answers:

3

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?

+4  A: 
INSERT INTO Employee 
    (EmployeeName, DepartmentId)
SELECT 
    'John Doe' AS EmployeeName, Id AS DepartmentId
FROM 
    Department WHERE DepartmentName = 'Accounting';
Mitch Wheat
Cool, that works great. Thanks very much.
Kevin Stembridge
+4  A: 

You can do:

insert into Employee (
    EmployeeName,
    DepartmentId
)
SELECT 'John Doe', Id
FROM Department
WHERE DepartmentName = 'Accounting'
AdaTheDev
A: 

Your query will fail in Oracle if there is more than one accounting department.

If you rely on this behavior, use this syntax:

INSERT
INTO    Employee
        (
        EmployeeName,
        DepartmentId
        )
SELECT  "John Doe",
        (
        SELECT  id
        FROM    Department
        WHERE   DepartmentName = 'Accounting'
        )

Otherwise, just use the SELECT FROM Department syntax proposed by others.

Note, however, that this syntax will insert John Doe twice or more, if there are multiple rows with name set to Accounting in Deparments.

Quassnoi
You're right, it would fail but that is the behaviour I would want as opposed to inserting two rows. I'm just using this to populate some test data. Thanks very much for the feedback.
Kevin Stembridge
`@Kevin Stembridge`: So you want it to fail or to insert two rows? My query will fail.
Quassnoi