I have one master table and few smaller table.
Master
table has C1 | C2 | C3 | C4 | C5 |
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
To insert records from multiple tables, use INSERT INTO SELECT statement. Here, we will insert records from 2 tables.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With