将特定列的值从一个表插入另一个表中的特定列

时间:2014-10-01 07:09:28

标签: sql insert multi-table

我在SQL中有两个表,每个表分别有12和16列。其中4个在两者中都很常见。

我需要的是我希望将一个表中这4列的值插入到另一个表的列中。

我尝试了以下内容:

INSERT INTO TABLE2 (IDCOMPANY,
                IDPLANT,
                IDTRAINING,
                IDEMPLOYEE,
                IDGRADE,
                IDDEPARTMENT,
                IDDESIGNATION,
                EMAIL,
                STATUS,
                CREATEDBY,
                CREATEDON)
        VALUES (@IDCOMPANY,
                @IDPLANT,
                @IDTRAINING,
                @IDEMPLOYEE,
        (SELECT IDGRADE,
         IDDEPARTMENT,
         IDDESIGNATION,
         EMPLOYEE_EMAIL 
         FROM TABLE1 
         WHERE EMPLOYEECODE=@EMPLOYEECODE ) ,
                @STATUS,
                @CREATEDBY,
                GETDATE())

其他列值是通过我的应用程序中的参数传递的,但是我希望从另一个表中列出四列IDGRADE,IDDEPARTMENT,IDDESIGNATION,EMPLOYEE_EMAIL

这可以吗????我需要一些帮助。

更新:运行时的上述查询会出现以下错误:

Msg 116, Level 16, State 1, Procedure USP_INSERT_HR, Line 219
Only one expression can be specified in the select list when the subquery 
is not introduced with EXISTS.
Msg 109, Level 15, State 1, Procedure USP_INSERT_HR, Line 217
There are more columns in the INSERT statement than values specified in 
the VALUES clause. The number of values in the VALUES clause must match the
number of columns specified in the INSERT statement.

2 个答案:

答案 0 :(得分:0)

您的代码应具有此结构。

INSERT INTO TABLE2
(IDCOMPANY,IDPLANT,IDTRAINING,IDEMPLOYEE,IDGRADE,IDDEPARTMENT,IDDESIGNATION,EMAIL,STATUS,CREATEDBY,CREATEDON)

SELECT @IDCOMPANY,@IDPLANT,@IDTRAINING,@IDEMPLOYEE,IDGRADE,IDDEPARTMENT,IDDESIGNATION,EMPLOYEE_EMAIL,@STATUS,@CREATEDBY,GETDATE())
FROM TABLE1 WHERE EMPLOYEECODE=@EMPLOYEECODE  

答案 1 :(得分:0)

编辑 - 现在问题得到了很大改善,请尝试以下方法(您可以在选择内部使用变量而不会出现问题)。 INSERT部分中的11列现在应该与11列值相匹配 - 6由@ Variables提供,4由SELECT FROM TABLE1提供,1由GETDATE提供()

INSERT INTO TABLE2 (IDCOMPANY, IDPLANT, IDTRAINING, IDEMPLOYEE, IDGRADE, IDDEPARTMENT,
                    IDDESIGNATION, EMAIL, STATUS, CREATEDBY, CREATEDON)
    SELECT @IDCOMPANY, @IDPLANT, @IDTRAINING, @IDEMPLOYEE,
           IDGRADE, IDDEPARTMENT, IDDESIGNATION, EMPLOYEE_EMAIL,
           @STATUS, @CREATEDBY, GETDATE()
     FROM TABLE1 
     WHERE EMPLOYEECODE=@EMPLOYEECODE

---结束编辑---

INSERT添加了全新的行,并且从您的问题中出现(虽然有点模棱两可,所以我只是在猜测)您希望将table1中4列的值添加到同一命名列中的table2中记录已存在

如果以上是真的,那么你需要使用UPDATE(而不是INSERT)。类似于下面的东西应该接近工作。

UPDATE TABLE2 AS T2
SET T2.IDCOMPANY = T1.IDCOMPANY, T2.IDPLANT = T1.IDPLANT, T2.IDTRAINING = T1.IDTTRAINING,
T2.IDEMPLOYEE = T1.IDEMPLOYEE
FROM TABLE2 JoinTbl
INNER JOIN TABLE1 AS T1
ON JoinTbl.EMPLOYEECODE = T1.EMPLOYEECODE