如何在sql server 2008中交换列值?

时间:2010-11-16 20:25:32

标签: sql sql-server sql-server-2008

我有一张名为Employee的表

 Eno     ename     AttributeValue      AttributeName  
 1       aa           a123             abc
 2       bbb          b123             dcf
 3       cc           c7sd             wew3

我想将AttributeValue列中的数据交换为AttributeNameAttributeName转换为AttributeValue

例如:

Eno     ename     AttributeValue   AttributeName  
1       aa        abc              a123
2       bbb       dcf              b123
3       cc        wew3             c7sd

8 个答案:

答案 0 :(得分:88)

UPDATE employee
SET AttributeValue = AttributeName, 
    AttributeName = AttributeValue

但是,除非两列具有完全相同的定义,否则您可能会丢失信息。

答案 1 :(得分:12)

Update employee
Set attributeValue = attributeName,
    attributeName = attributeValue

答案 2 :(得分:5)

update Employee set AttributeValue = AttributeName, AttributeName = AttributeValue

答案 3 :(得分:3)

这是非常好的例子

SELECT * from employees;
Go

DECLARE @temp as varchar(20)
update employees
set    @temp = fname,
       fname = lname,
       lname = @temp
WHERE  deptno = 10;
GO

SELECT * from employees;

Result

答案 4 :(得分:2)

所有以前的技术对于大表来说都很慢,他们移动日期而不是重命名列,这是一个简单的解决方案:

ALTER TABLE "amplitude"
RENAME COLUMN "start_hour_displayed" TO "temp";

ALTER TABLE "amplitude"
RENAME COLUMN "start_hour" TO "start_hour_displayed";

ALTER TABLE "amplitude"
RENAME COLUMN "temp" TO "start_hour";

如果你有链接功能的视图,你必须先备份它们并在之后恢复它们。

答案 5 :(得分:1)

Declare @myTable Table (id int, first_name varchar(50), last_name varchar(50));

Select * from Student

Insert Into @myTable (id, first_name, last_name) Select id, last_name, first_name from Student

    MERGE
    INTO    Student std
    USING @myTable tmp
    ON std.id = tmp.id
    WHEN MATCHED THEN
    UPDATE
    SET std.first_name = tmp.first_name,
    std.last_name = tmp.last_name;

Select * from Student

<强>输出

Query Result Screenshot

答案 6 :(得分:0)

只需在一次更新中交换两列:

Update registration
Set AttributeName = AttributeValue ,
    AttributeValue = AttributeName where id in (1,2,3)

答案 7 :(得分:0)

更新员工 SET AttributeValue = AttributeName,     AttributeName = AttributeValue最好不要正确创建一个临时列并尝试代码 更新员工 SET temp =属性名称 然后再 更新员工 SET AttributeName = AttributeValuee 再次

更新员工 SET AttributeValuee =临时