0

我在 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.
4

2 回答 2

1

您的代码应该具有这种结构。

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  
于 2014-10-01T07:24:01.037 回答
0

编辑-现在问题得到了很大改善,请尝试以下操作(您可以在选择中使用变量而不会出现问题)。INSERT 部分中的 11 列现在应与 11 列值匹配 - 6 个由 @ 变量提供,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
于 2014-10-01T07:28:22.623 回答