如何在 T-SQL 中插入另一个 table 的列?

How to insert a column from another table in T-SQL?

我有两个 table 我需要合并而不创建新的 view/table。基本上,我只需要将一列添加到现有的 table 中,该 table 取自另一个 table.

table1 看起来像这样:

table2 看起来像这样:

我需要一个 table,它看起来就像 table2,但有一个额外的列:programs_total。如果第一列没有这样的id,我希望第二列有NULL。在此示例中,我希望带有 id=72_200 的原始数据在 programs_total 列中具有 NULL

我尝试了以下脚本:

-- adding a new column 
ALTER TABLE table2
ADD programs_total BIGINT NULL;

-- inserting new data
INSERT INTO table2 (programs_total)
SELECT programs_total
FROM table1

但它会产生以下错误:

Msg 515, Level 16, State 2, Line 4
Cannot insert the value NULL into column 'id', table 'stb.dbo.table2'; column does not allow nulls. INSERT fails.
The statement has been terminated.

我想它会尝试插入三个新行,而不是将列与现有的列连接起来。我如何告诉它将该列连接到现有行?

或者我做错了什么?

看来您确实想要UPDATE:

UPDATE t2
SET t2.total_programs = t1.total_programs
FROM dbo.table2 t2
     JOIN dbo.table1 t1 ON t2.id = t1.id;

但是,如果 table1 中的 id 值未出现在 table2 中,并且您想将这些值插入 table2 中好吧,你会想要一个 MERGE:

MERGE dbo.Table2 AS T2
USING dbo.TAble1 AS T1 ON T2.id = T1.id
WHEN MATCHED THEN
    UPDATE 
    SET total_programs = t1.total_programs
WHEN NOT MATCHED THEN
    INSERT (id,total_programs)
    VALUES(T1.id,T1.total_programs);

或者您可以将它写成一个更新插入,如下所示:

UPDATE t2
SET t2.total_programs = t1.total_programs
FROM dbo.table2 t2
     JOIN dbo.table1 t1 ON t2.id = t1.id;

INSERT INTO dbo.Table2(id,total_programs)
SELECT t1.id,
       t1.total_programs
FROM dbo.Table1 t1
WHERE NOT EXISTS (SELECT 1
                  FROM dbo.Table2 t2
                  WHERE t2.id = t1.id);

Description: you need an UPDATE, not an INSERT. The former will add a new row, hence your error for non-nullable columns

尝试以下测试,如果看起来不错,运行 UPDATE 语句:

SELECT 
     t2.*
    ,table1.programs_total   /* new column*/
FROM table2 t2
LEFT OUTER JOIN table1 on t2.ID = table1.id  ;

更新:

UPDATE t2
SET total_programs = table1.programs_total
FROM table2 t2
LEFT OUTER JOIN table1 on t2.ID = table1.id  ;

首先你可以获取数据:

SELECT 
    table2.id,
    table2.total_duration,
    table1.programs_total
FROM
    table2
    LEFT JOIN table1
    ON table2.id = table1.id

如果您需要此数据作为新数据 table,您可以像这样简单地添加一个 INTO:

SELECT 
    table2.id,
    table2.total_duration,
    table1.programs_total
INTO
    table3
FROM
    table2
    LEFT JOIN table1
    ON table2.id = table1.id

'table3' 是新 table 的名称。

您需要更新该列:

UPDATE table2 
SET total_programs = B.total_programs
FROM table1 A
JOIN table2 B
ON A.ID = B.ID

感谢您提出如此详细的问题。你也可以使用子查询来更新table2。

update table2
set programs_total=(select programs_total from table1 where table1.id=table2.id)