将数据从一个表插入另一个具有相同列名的另一个表的存储过程

007*_*007 8 sql t-sql sql-server stored-procedures

我有一张主表和几张小表.

  • Master 表有 C1 | C2 | C3 | C4 | C5 |
  • 一张小桌子 C1 | C2 | C3 |

(还有@C1一个变量,其值与Master表中的C1值相匹配).

列名匹配两个表.我想创建一个存储过程从插入值Master表(C1,C2,和C3更小的表)( C1, C2, C3).

我的努力:

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
Run Code Online (Sandbox Code Playgroud)

请帮忙

谢谢

mar*_*c_s 10

您需要使用INSERT INTO ... SELECT .....语法 - 不VALUES涉及关键字:

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
Run Code Online (Sandbox Code Playgroud)