简体   繁体   English

如何将列从一个表复制到 SQL 服务器中的另一个表

[英]How to copy column from one table into another table in SQL Server

I want to copy column state_name from table state into table district.我想将表 state 中的列 state_name 复制到表区中。 here is my query.这是我的查询。

This code is working on mysql but not in SQL Server此代码适用于 mysql 但不适用于 SQL 服务器

UPDATE district,state
SET    district.state_name = state.state_name
WHERE  district.state_id = state.id

在此处输入图像描述

This is the state table这是state

在此处输入图像描述

This is the district table这是district

In SQL Server, the corresponding syntax might be:在 SQL 服务器中,对应的语法可能是:

UPDATE district
     SET state_name = s.state_name
    FROM state s
    WHERE district.state_id = s.id;

This is more commonly written using an explicit JOIN :这更常使用显式JOIN编写:

UPDATE d
     SET state_name = s.state_name
    FROM district d JOIN
         state s
         ON d.state_id = s.id;

However, you probably shouldn't be updating the value at all.但是,您可能根本不应该更新该值。 Just use a JOIN to get the state name when you need it.只需在需要时使用JOIN获取 state 名称。

In T-SQL, an UPDATE can only be followed by a single object afterwards.在 T-SQL 中, UPDATE之后只能跟一个 object。 I suspect what you want woulkd be:我怀疑你想要的是:

UPDATE d
SET state_name = s.state_name
FROM dbo.district d
     JOIN dbo.state ON d.state_id = s.id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM