如何将一列插入到 SQL Server 中同一表中的另一列中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5541916/
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 10:01:18  来源:igfitidea点击:

How to insert one column into other column within the same table in SQL Server

sqlsql-serversql-server-2008

提问by kumar

I need to insert one column's data into another column within the same table.

我需要将一列的数据插入同一个表中的另一列。

Can anybody tell me how to write this?

谁能告诉我这个怎么写?

Thanks

谢谢

回答by Cade Roux

UPDATE table
SET col_2 = col_1

回答by Doliveras

If you want to copy data from one column to another on the same table:

如果要将数据从同一表中的一列复制到另一列:

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

IF you want to add a new column and copy the original data to that column:

如果要添加新列并将原始数据复制到该列:

ALTER TABLE table_name
   ADD new_column_name column_type NULL

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

回答by Jeffrey L Whitledge

If you want the column to be non-nullable, then you can set it to a default value before doing the update.

如果您希望该列不可为空,则可以在进行更新之前将其设置为默认值。

begin transaction
alter table Song add SortArtist nvarchar(128) not null default N''
go
update Song set SortArtist = Artist
commit transaction

回答by gady RajinikanthB

alter table [dbo].[GetPermission]
add username1 varchar(100) ----------------ading new column username1

更改表 [dbo].[GetPermission]
添加 username1 varchar(100) ----------------ading 新列 username1

update GetPermission set username1=username

更新 GetPermission 设置 username1=用户名