[英]SQL Server - change column if existing in other table?
Playing around with SQL Server 2008 and I have a table People
with columns: 玩SQL Server 2008,我有一个表
People
列:
Name | City | Born | ...
and another table Change
with columns: 和另一个表
Change
列:
OldName | NewName
Now I would like to change Name
in the table People
something like this: if there is the same OldName
in table Change
as the Name
in People
then change the Name
in People
to the NewName
in Change
. 现在我想改
Name
表中的People
是这样的:如果有相同OldName
表Change
为Name
的People
然后更改Name
在People
的NewName
的Change
。
Any easy way? 任何简单的方法?
Oh and another question to this: if the Name
in People
would be the primary key (or let say Name
and City
would be composite key), would it be much harder to change the name? 哦,还有另外一个问题:如果
People
的Name
是主键(或者说Name
和City
是复合键),更改名称会更难吗? Thx 谢谢
Answer1) ANSWER1)
UPDATE people,change
SET people.name = change.newname
WHERE people.name = change.oldName
EDIT with inner Join syntax: 使用内部连接语法编辑 :
UPDATE people
SET people.name = change.newName
FROM people
INNER JOIN change ON people.name = change.oldName
I don't have a SQL Server to test that on, but based on online examples, it should work. 我没有SQL Server来测试它,但基于在线示例,它应该工作。
/Edit /编辑
Answer2) As long as you still maintain uniqueness in the key it wouldn't be difficult to change at all. 答案2)只要你仍然保持钥匙的独特性,就不会有任何变化。 As soon as you cause a collision you would get an error.
一旦发生碰撞,就会出现错误。 For this reason it would be best to have an auto-incrementing ID field in people that would be your PK
因此,最好在人员中使用自动递增ID字段作为您的PK
You might be better off to add a PeopleId
column to the People
table, and replace the OldName
column in the Change
table with a PeopleId
column that has a foreign key relationship back to the People
table: 最好将
PeopleId
列添加到People
表中,并将Change
表中的OldName
列替换为具有返回People
表的外键关系的PeopleId
列:
People: 人:
PeopleId | Name | City | Born
-------------------------------------------
1 | Fred | New York | 1/1/1980
2 | Wilma | Boston | 1/1/1980
Change: 更改:
PeopleId | NewName
----------------------
1 | Barney
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.