INSERT SELECT 语句只有一列用于 SELECT

INSERT SELECT statement with only one column for SELECT

我正在使用 SQL Server Management Studio 18,并且我有以下 tables 和以下列:

表A

[ID]
[Name]
[InternalEmplID]

表B

[ID]
[InternalEmplID]
[Month]
[Year]

我想在 TableB 中做一个 INSERT SELECT,可能像下面这样:

INSERT INTO TableB
(InternalEmplID, Month, Year)
VALUES
((SELECT InternalEmplIDFROM TableA WHERE Name = 'John Smith'), 'July', '2020')

基本上,我只想创建一个 INSERT SELECT,我从另一个 table (InternalEmplID) 中抓取一个列,然后是其他列 (MonthYear),我想添加不依赖于来自另一个 table 的 columns/data 的数据。这可能吗?我对 INSERT SELECT 不太熟悉,所以这对我来说是全新的。

如果 如果 select returns 超过一行,您的查询将失败。更灵活的选择是使用 INSERT ... SELECT 语法并在附加列中提供文字值:

INSERT INTO TableB (InternalEmplID, Month, Year)
SELECT InternalEmplIDFROM, 'July', '2020' TableA WHERE Name = 'John Smith'

你已经很接近了……就这样吧

INSERT INTO TableB (
    InternalEmplID, Month, Year
)
SELECT
    InternalEmplID, 'July', '2020'
FROM
    TableA
WHERE
    Name = 'John Smith'