0

我正在尝试根据帐号是否已在现有数据中来更新或插入数据。首先,我使用这个将新变量添加到表中已有帐户编号的变量中

drop table #test1
select a.*, B.Delq_Sep12, b.Bal_Sep12, b.Queue_Sep12
into #test1
from  pcd1 a
left join #pcd_sep12  b on  (a.ACCOUNT_NUMBER = B.account_number)

然后我将#pcd_sep12中帐号不在test1(上面创建)中的所有记录添加到test1中

INSERT #test1
SELECT * FROM #pcd_sep12 WHERE account_number NOT IN(SELECT account_number FROM #test1)

我收到错误列名或提供的值的数量与表定义不匹配。

我意识到这是因为字段数量不同,但有没有办法解决这个问题?

4

3 回答 3

2

为什么不使用MERGE(又名“upsert”)语句?

MERGE INTO pcd1 M
USING (SELECT * FROM #pcd_sep12) src ON M.account_number = src.account_number
WHEN MATCHED
-- UPDATE stuff
WHEN NOT MATCHED BY TARGET
-- INSERT stuff;

这样你就不需要临时表或任何测试:这些在负载下不会是并发安全的

于 2012-10-16T12:12:35.353 回答
0

if i am not mistaken, your #test1 table has columns from pcd1 table also. but in your second query, you are only selecting from #pcd_sep12.

于 2012-10-16T12:09:35.183 回答
0

您必须像这样指定列

INSERT INTO #test1 (column1, column2, column3)
(SELECT column1, column2, column3 FROM #pcd_sep12 WHERE account_number NOT IN(SELECT account_number FROM #test1))
于 2012-10-16T12:07:18.670 回答