📅  最后修改于: 2023-12-03 15:20:14.784000             🧑  作者: Mango
SQL Server provides powerful tools for inserting data from one table into another table. The INSERT INTO SELECT statement is used to insert data from one table to another table. This statement can be very useful when you need to create a new table with the same data as an existing table.
The basic syntax of the INSERT INTO SELECT statement is as follows:
INSERT INTO new_table (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM old_table
Suppose we have two tables: employees and new_employees. The employees table contains the following data:
| employee_id | first_name | last_name | salary | | ----------- | ---------- | ----------- | ------ | | 1 | John | Doe | 50000 | | 2 | Jane | Smith | 55000 | | 3 | Michael | Johnson | 60000 | | 4 | Sarah | Thompson | 65000 |
We want to copy the data from the employees table to the new_employees table. We can use the INSERT INTO SELECT statement as follows:
INSERT INTO new_employees (employee_id, first_name, last_name, salary)
SELECT employee_id, first_name, last_name, salary
FROM employees
The new_employees table will now contain the same data as the employees table.
In summary, the INSERT INTO SELECT statement in SQL Server is a powerful tool for copying data from one table to another table. It can save you a lot of time and effort when creating new tables with the same data as existing tables. Understanding how to use this statement will make you a more efficient and effective SQL programmer.