【问题标题】:How to add a column in a table from another table having common id column in both the tables in SQL Server?如何从另一个表中添加一个表中的列,该表在 SQL Server 的两个表中具有公共 id 列?
【发布时间】:2020-07-14 14:11:21
【问题描述】:

我正在尝试使用 table2 中的 Column2 更新 table1,其中 id 应该匹配,同时将 table2 中的 Column2 值插入 SQL Server 的 table1 中。

我尝试使用以下 2 组代码,但它不起作用。 谁能帮我解决这个问题?

alter table table1
add Column2 varchar(20)

insert into table1
Select t2.Column2
    from table1 as t1
    inner join table2 as t2
    on t1.id = t2.id

还有,下面还有:

Update table1
Set Column2 = (Select t2.Column2
        from table1 as t1
        inner join table2 as t2
        on t1.id = t2.id)

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。但听起来你可能想要merge
  • 第二个查询很可能会出现“子查询返回多于一行”的错误。 FROM 中的table1UPDATE 子句中的table1相同的引用。您应该使用UPDATE ...SET... FROM... JOIN 查询。

标签: sql sql-server


【解决方案1】:
Update t1
Set Column2 = t2.Column2
    from table1 as t1
    inner join table2 as t2
    on t1.id = t2.id

【讨论】:

  • 谢谢!工作正常。
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 2022-10-23
  • 2022-07-18
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多