How do I swap column values in sql server 2008?

后端 未结 8 535
春和景丽
春和景丽 2020-12-08 09:40

I have a table called Employee

 Eno     ename     AttributeValue      AttributeName  
 1       aa           a123             abc
 2       bbb          b123           


        
相关标签:
8条回答
  • 2020-12-08 09:50

    All the previous techniques are slow for big tables they move data instead of renaming columns, this is a simple solution:

    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";
    

    If you have views of functions linked you have to backup them before and restore them after.

    0 讨论(0)
  • 2020-12-08 09:50
    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
    

    Output

    Query Result Screenshot

    0 讨论(0)
  • 2020-12-08 09:52
    Update employee
    Set attributeValue = attributeName,
        attributeName = attributeValue
    
    0 讨论(0)
  • 2020-12-08 09:53

    Just swap both columns in a single update:

    Update registration
    Set AttributeName = AttributeValue ,
        AttributeValue = AttributeName where id in (1,2,3)
    
    0 讨论(0)
  • 2020-12-08 09:56
    UPDATE employee
    SET AttributeValue = AttributeName, 
        AttributeName = AttributeValue
    

    However, unless both columns have the exact same definition, you risk losing information.

    0 讨论(0)
  • 2020-12-08 10:05

    UPDATE employee SET AttributeValue = AttributeName, AttributeName = AttributeValue its not correct better to create one temp column and try the code UPDATE employee SET temp= AttributeName then again UPDATE employee SET AttributeName = AttributeValuee again

    UPDATE employee SET AttributeValuee= temp

    0 讨论(0)
提交回复
热议问题