如何在SQL Server中使用Sub-SELECT插入外键

Kev*_*dge 5 sql sql-server subquery

我刚刚开始使用SQL Server,而且我在填充测试数据时遇到了麻烦.我有两个表,其中一个具有另一个的外键,我希望能够使用以下SQL插入新记录:

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

这个语句在Oracle中工作正常但在SQL Server中我得到一个错误说:

Subqueries are not allowed in this context.
Run Code Online (Sandbox Code Playgroud)

有人知道在SQL Server中执行此操作的正确方法吗?

Mit*_*eat 10

INSERT INTO Employee 
    (EmployeeName, DepartmentId)
SELECT 
    'John Doe' AS EmployeeName, Id AS DepartmentId
FROM 
    Department WHERE DepartmentName = 'Accounting';
Run Code Online (Sandbox Code Playgroud)


Ada*_*Dev 5

你可以做:

insert into Employee (
    EmployeeName,
    DepartmentId
)
SELECT 'John Doe', Id
FROM Department
WHERE DepartmentName = 'Accounting'
Run Code Online (Sandbox Code Playgroud)