如何在sqlserver中将数据从一个表的多行复制到另一个表



我有两个具有以下结构的表:

表A:

id_A    col1
 1      val1
 2      val2
 3      val3
 ...    ....

表B:

id_B  mycol   id_A_val
 1    smval1    null
 2     null      1
 3     null      2
...    ...       ...

我想将表A的col1中的值复制到表B的mycol中这是我的预期结果:

预期:

id_B  mycol   id_A_val
 1    smval1    null
 2    val1      1
 3    val2      2
...    ...      ...

我尝试了几种SQL UPDATE的组合。这是我最近尝试的一次,但它抛出了一个错误,说"Subquery返回了超过1个值。"

尝试:

UPDATE [dbo].[Table_B] 
SET MYCOL = (SELECT inst.[COL1] FROM [dbo].[TABLE_A] a,  [dbo].[TABLE_B] b
WHERE a.[ID_A] = b.[ID_A_VAL] AND b.ID_A_VAL IS NOT NULL)

有人能指出正确的方向来获得有效的查询吗?

试试这个:

update
    b
set
    mycol=table_a.col1
from table_b b
inner join table_a on
    b.id_A_val=table_a.id_A

您的错误是在赋值(select)中使用了非常旧的样式JOIN正确的语法应该是

UPDATE Table_B
SET MYCOL = (SELECT a.COL1 
             FROM TABLE_A a
             WHERE a.ID_A = Table_B.ID_A_VAL AND Table_B.ID_A_VAL IS NOT NULL)

这种语法是有效的,但通常在这些情况下应用INNER JOIN

UPDATE table_b
SET  mycol = table_a.COL1
FROM table_b 
INNER JOIN table_a ON table_b.ID_A_VAL = table_a.id_A

试试这个

  UPDATE tableb
    SET mycol=a.col1
    FROM tableb  b
        INNER JOIN tablea a ON a.id_A=b.id_A_val    
    WHERE b.mycol is null

您修改的关联子查询

UPDATE [dbo].[Table_B] 
SET MYCOL = (
             SELECT A.[COL1]
             FROM [dbo].[TABLE_A] a
             WHERE a.[ID_A] = [dbo].[Table_B].[ID_A_VAL]               
             )
WHERE [dbo].[Table_B].[ID_A_VAL] IS NOT NULL

相关内容

  • 没有找到相关文章

最新更新