如何使用额外的列将临时表添加到另一个临时表

时间:2016-05-10 11:44:38

标签: sql sql-server dynamic-sql

CREATE TABLE #EmpPcodes
(
   YearMonth        INT,
   YEAR             INT,
   MONTH            INT,
   RunNo            INT,
   Amount           NUMERIC(18, 3),
   GroupCode        NvarCHAR(30),
   GroupName        NvarCHAR(250),
   GroupAName       NvarCHAR(250),
   PayrollGroup     INT,
   EmployeeId       INT
)    
CREATE TABLE #pArrangeAllcode
(
   YearMonth        INT,
   YEAR             INT,
   MONTH            INT,
   RunNo            INT,
   Amount           NUMERIC(18, 3),
   GroupCode        NvarCHAR(30),
   GroupName        NvarCHAR(250),
   GroupAName       NvarCHAR(250),
   PayrollGroup     INT,
   EmployeeId       INT,
   CodeArrange      INT
)

INSERT INTO #pArrangeAllcode 
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, 
GroupAName, PayrollGroup, EmployeeId,
FROM dbo.#EmpPcodes 

SELECT * FROM #pArrangeAllcode

我希望将#EmPcodes临时表中的数据转换为#pArrangeAllcode 但它有额外的专栏我以后会用它......我总是得到这个错误:

Insert Error: Column name or number of supplied values does not match table definition.

任何帮助?

4 个答案:

答案 0 :(得分:2)

实际上你在insert语句中缺少一列,而且还需要一些值:

使用它:

INSERT INTO #pArrangeAllcode 
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, 
GroupAName, PayrollGroup, EmployeeId,NULL
FROM dbo.#EmpPcodes

答案 1 :(得分:1)

使用以下查询插入记录。

INSERT INTO #pArrangeAllcode 
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, 
GroupAName, PayrollGroup, EmployeeId,NULL
FROM dbo.#EmpPcodes 

答案 2 :(得分:1)

CodeArrange#pArrangeAllcode表中存在的额外列。由于它是NOT NULL列,您可以跳过插入块中的特定列名,并明确提到列名是INSERT语句。

INSERT INTO #pArrangeAllcode (YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId)
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId
FROM #EmpPcodes 

或者如果您想在CodeArrange列中存储一些虚拟值,则传递NULL

INSERT INTO #pArrangeAllcode (YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId, CodeArrange)
SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId, NULL
FROM #EmpPcodes 

答案 3 :(得分:0)

INSERT INTO #pArrangeAllcode 
SELECT dbo.#EmpPcodes.*, NULL
FROM dbo.#EmpPcodes