Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure to Insert Data from one table to another with same column names

I have one master table and few smaller table.

  • Master table has C1 | C2 | C3 | C4 | C5 |
  • A small table has C1 | C2 | C3 |

Also @C1 (a variable that has a value which matches the value of C1 in Master table.

The column names matches for both table. I want to create a stored procedure which inserts values from Master table (C1, C2, and C3) to smaller table (C1, C2, C3).

My effort:

Create proc Schema.Proc
(@C1 int)
AS
BEGIN
INSERT INTO SmallTable
(C1, C2, C3) --- Columns of smaller table
Values (SELECT C1, C2, C3 ---Columns of Master table
FROM MasterTable)
WHERE C1 = @C1 --- Where value of C1 of Master table matches the value of @C1
END

Please help

Thank you

like image 866
007 Avatar asked Jan 07 '13 22:01

007


People also ask

How do you insert values from a table in two different tables?

To insert records from multiple tables, use INSERT INTO SELECT statement. Here, we will insert records from 2 tables.

How can we insert values from two tables in single query?

The T-SQL function OUTPUT, which was introduced in 2005, can be used to insert multiple values into multiple tables in a single statement. The output values of each row that was part of an INSERT, UPDATE or DELETE operation are returned by the OUTPUT clause.

Can we insert data from one table to another table?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

Can we use insert statement in stored procedure?

Stored Procedure for Select, Insert, Update, DeleteThe INSERT statement is used to add new rows to a table. The UPDATE statement is used to edit and update the values of an existing record. The DELETE statement is used to delete records from a database table.


2 Answers

You need to use the INSERT INTO ... SELECT ..... syntax - no VALUES keyword involved:

CREATE PROCEDURE Schema.Proc
   (@C1 int)
AS
BEGIN
    INSERT INTO SmallTable(C1, C2, C3) --- Columns of smaller table
        SELECT C1, C2, C3 ---Columns of Master table
        FROM MasterTable
        WHERE C1 = @C1 --- Where value of C1 of Master table matches the value of @C1
END
like image 73
marc_s Avatar answered Oct 17 '22 03:10

marc_s


You were close! As long as C1, C2 and C3 are the same data types this should work.

Create proc Schema.Proc
(@C1 int)
AS
BEGIN
INSERT INTO SmallTable
(C1, C2, C3) --- Columns of smaller table
SELECT C1, C2, C3 ---Columns of Master table
FROM MasterTable
WHERE C1 = @C1
END
like image 41
AdamV Avatar answered Oct 17 '22 05:10

AdamV