SQL Server : INSERT from one table to another table

后端 未结 3 1490
温柔的废话
温柔的废话 2021-01-23 03:25

I am facing a problem regarding inserting data from one table to another table, with the same table structure, but with different column positions.

Example:

Tabl

相关标签:
3条回答
  • 2021-01-23 03:40

    It's simple just reorder columns during insert:

    INSERT INTO `emp1` (Name, Salary, Age)
    SELECT Name, Salary, Age FROM `emp2`;
    
    0 讨论(0)
  • 2021-01-23 03:42

    You can (or as @marc_s mentioned should) specify columns.

    Doing that you can change a structure of these tables (could happen, right?) without any consequences (except if you delete these columns). Your code still working.

    Moreover specifying columns name it's just more readable for anybody. You don't need to call sp_help or any other commands to check the structure (table schema).

    BTW having a primary key in both tables or any table will throw an exception if not specifying the sought columns only:

    If an INSERT statement violates a constraint or rule, or if it has a value incompatible with the data type of the column, the statement fails and an error message is returned.

    If INSERT is loading multiple rows with SELECT or EXECUTE, any violation of a rule or constraint that occurs from the values being loaded causes the statement to be stopped, and no rows are loaded.

        INSERT INTO emp1 (Name
            ,Age 
            ,Salary )
        SELECT Name
            ,Age 
            ,Salary
        FROM emp2
    
    0 讨论(0)
  • 2021-01-23 04:01

    test this query , it should work:

    insert into emp1 select Name, Age, Salary from emp2;
    

    and I suggest you to read this tutorial.

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