将同一表中一列的值更新到 SQL Server 中的另一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16180589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:58:08  来源:igfitidea点击:

Update values from one column in same table to another in SQL Server

sqlsql-serversql-update

提问by Keven

I'm trying to overwrite values that are found in TYPE1 with values that are found in TYPE2.

我试图用在 TYPE2 中找到的值覆盖在 TYPE1 中找到的值。

I wrote this SQL to try it out, but for some reason it isn't updating:

我写了这个 SQL 来尝试一下,但由于某种原因它没有更新:

select * from stuff

update stuff
set TYPE1 = TYPE2
where TYPE1 is null;

update stuff
set TYPE1 = TYPE2
where TYPE1 ='Blank';

http://www.sqlfiddle.com/#!3/a4733/17

http://www.sqlfiddle.com/#!3/a4733/17

Any reason why my values in TYPE1 are not updating?

我在 TYPE1 中的值没有更新的任何原因?

回答by Sparky

This works for me

这对我有用

select * from stuff

update stuff
set TYPE1 = TYPE2
where TYPE1 is null;

update stuff
set TYPE1 = TYPE2
where TYPE1 ='Blank';

select * from stuff

回答by Bob Taylor

UPDATE a
SET a.column1 = b.column2
FROM myTable a 
INNER JOIN myTable b
on a.myID = b.myID

in order for both "a" and "b" to work, both aliases must be defined

为了使“a”和“b”都能工作,必须定义两个别名

回答by Gy?ri Sándor

UPDATE TABLE_NAME SET COLUMN_A = COLUMN_B;

Much easier. At least on Oracle SQL, i don't know if this works on other dialects as well.

容易多了。至少在 Oracle SQL 上,我不知道这是否也适用于其他方言。

回答by Ahmed Mahmoud AbdElbaset

This answer about updating column from a part of another column in the same table.

这个关于从同一表中另一列的一部分更新列的答案。

update T1
set domainname = (New value) --Example: (SELECT LEFT(TableName.col, CHARINDEX('@',TableName.col)-1) STRIPPED_STRING FROM TableName where TableName.col = T2.Emp_ID)
from TableName T1
INNER JOIN
    TableName T2
ON 
    T1.ID= T2.ID;

回答by Hyman

You put select query before update queries, so you just see initial data. Put select * from stuff;to the end of list.

您将选择查询放在更新查询之前,因此您只会看到初始数据。放在select * from stuff;列表的末尾。

回答by Ian Kenney

Your select statement was before the update statement see Updated fiddle

您的选择语句在更新语句之前,请参阅更新的小提琴

回答by Tarek.Iraqi

update TABLE_1 a set COLUMN_1 = (select COLUMN_2 from TABLE_1 b where a.ID = b.ID)