插入前比较几列的值

时间:2013-10-04 19:36:08

标签: sql sql-server sql-server-2008

假设我有一个临时表#t包含列(MyGroup,FSGRoup,Account,BrokerCode,AccountType,NewInvestmentType,AccountOrder,LPI,LPII,LPIII),其中包含完整的行数。

我有另一个表#t2,它具有相同的布局,只有#t中包含的一部分行。如果列MyGroup,FSGRoup,Account,BrokerCode,AccountType,NewInvestmentType,AccountOrder上没有匹配,我想将#t但不在#t2中的行插入到#t2中。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

如果您不想使用合并语句,如前所述,您可以执行以下操作。第一个查询使用外部联接来获取#t中但不在#t2中的行,并将它们放入第三个临时表#t3中。第二个查询将它们从#t3放入#t2。

SELECT t.MyGroup, t.FSGRoup, t.Account, t.BrokerCode, t.AccountType, t.NewInvestmentType, t.AccountOrder, t.LPI, t.LPII, t.LPIII
INTO #t3
FROM #t t
LEFT OUTER JOIN #t2 t2
ON t.MyGroup = t2.MyGroup AND t.FSGRoup = t2.FSGRoup AND t.Account = t2.Account AND t.BrokerCode = t2.BrokerCode AND t.AccountType = t2.AccountType AND t.NewInvestmentType = t2.NewInvestmentType AND t.AccountOrder = t2.AccountOrder
WHERE t2.MyGroup IS NULL 
/*Assuming that MyGroup can't be null.  If it can, use a column that can't.*/

INSERT INTO #t2
SELECT MyGroup, FSGRoup, Account, BrokerCode, AccountType, NewInvestmentType, AccountOrder, LPI, LPII, LPIII
FROM #t3

答案 1 :(得分:0)

假设您使用的是sql 2008+,这正是合并命令的用途(除其他外)

有一个很好的简单解释,请查看使用合并的this question - 还有一点点搜索。 MS文档虽然有点令人困惑。

ADDED

搞砸了,意味着包括this link关于合并基础的好文章。

答案 2 :(得分:0)

合并是一个很好的解决方案,但是当有多个操作(如插入,更新和删除)一次完成时,建议使用它。 因为这里的要求是将#t中的数据插入到#t中,这不属于#t,除了会这样做

insert into #t2(
MyGroup, FSGRoup, Account, BrokerCode, AccountType, NewInvestmentType, AccountOrder, LPI, LPII, LPIII)

select MyGroup, FSGRoup, Account, BrokerCode, AccountType, NewInvestmentType, AccountOrder, LPI, LPII, LPIII from #t 
except
select MyGroup, FSGRoup, Account, BrokerCode, AccountType, NewInvestmentType, AccountOrder, LPI, LPII, LPIII from #t2

这比之前发布的其他两个解决方案更有效,更可靠