Open In App

Insert Multiple Values Into Multiple Tables in SQL Server

Last Updated : 28 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To insert multiple values into multiple tables in SQL Server, use the OUTPUT clause.

The SQL OUTPUT clause allows to insert multiple values into multiple tables in a single query. Output clause clause in SQL is used to capture data affected by Data Manipulation Language (DML) statements like INSERT, UPDATE, or DELETE.

Syntax

Syntax to insert multiple values into multiple tables in SQL Server is:

INSERT INTO Table1 (Col1, Col2)OUTPUT inserted.Col1, inserted.Col2INTO Table2VALUES(‘Value1’, ‘Value2’)GO

How to Insert Multiple Values Into Multiple Tables in SQL Server

Use the OUTPUT clause with INSERT INTO statement to insert multiple values into multiple tables in the SQL server

Example

In this example, we will insert multiple values into two tables using an INSERT INTO statement with OUTPUT clause.

First we are creating 2 sample tables using the below queries:

CREATE TABLE GeekTable1 (
Id1 INT,
Name1 VARCHAR(200),
City1 VARCHAR(200)
);

an

CREATE TABLE GeekTable2 (
Id2 INT,
Name2 VARCHAR(200),
City2 VARCHAR(200)
);

GO

Now, let us Insert values into two tables together:

INSERT INTO GeekTable1 (Id1, Name1, City1)
OUTPUT inserted.Id1, inserted.Name1, inserted.City1
INTO GeekTable2
VALUES (1, 'Komal', 'Delhi'),
(2, 'Khushi', 'Noida');

GO

Select data from both the tables:

SELECT * FROM GeekTable1;
GO
SELECT * FROM GeekTable2;
GO

Output: When we run the above query, we will see that there are two rows each in the table:

GeekTable1:

Id1 Name1 City1
1 Komal Delhi
2 Khushi Noida

GeekTable2:

Id2 Name2 City2
1 Komal Delhi
2 Khushi Noida


Next Article
Article Tags :

Similar Reads