Insert into multiple records.
To insert multiple records at the same time in SQL Server, you can use the INSERT INTO statement with a SELECT statement or by providing multiple sets of values.
1- Using INSERT INTO with SELECT:
INSERT INTO table_name (column1, column2, column3, ...)
SELECT value1, value2, value3, ...
FROM another_table
WHERE condition;
In this method, you can specify the columns you want to insert data into and then provide a SELECT statement that retrieves the values from another table or combines them using expressions.
For example, if we have an "Employees" table and want to insert records from a "TempEmployees" table into it, we can use the following syntax:
INSERT INTO Employees (EmployeeID, FirstName, LastName)
SELECT EmployeeID, FirstName, LastName
FROM TempEmployees;
2- Using INSERT INTO with multiple sets of values:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...),
(value4, value5, value6, ...),
(value7, value8, value9, ...);
With this approach, you provide multiple sets of values separated by commas, enclosed within parentheses. Each set represents a separate record to be inserted into the table.
For example, if we want to insert three new employees into the "Employees" table, we can use the following syntax:
INSERT INTO Employees (EmployeeID, FirstName, LastName)
VALUES (1, 'John', 'Doe'),
(2, 'Jane', 'Smith'),
(3, 'Michael', 'Johnson');
In this case, three records will be inserted into the "Employees" table with the specified values.
Both methods allow you to insert multiple records in a single SQL statement, providing efficiency and reducing the number of round trips to the database.
It's important to ensure that the number and order of columns in the INSERT INTO statement match the target table's structure, and the data types and constraints are correctly adhered to.