如何将SELECT的结果添加到表中

时间:2012-03-08 15:11:59

标签: sql sql-server stored-procedures

我有一个SQL select语句,它正在比较两个表。我得到行相同的值。现在我在我需要将这些添加到新表(coftReconciliationMatches)的过程中得到了这个。该表格包含所有相同的列,但另外一列只有MatchOrNoMatch'。我需要传递匹配的行的值,还需要通过' Match'到专栏' MatchOrNoMatch'

这是我拥有的SQL脚本的当前部分;

SELECT * 
  FROM dbo.coftReconciliationFileInfo AS a 
 WHERE EXISTS (SELECT * 
                 FROM dbo.coftPreReconciliationInfo AS b 
                WHERE a.Rec_PK = b.Rec_PK 
                  AND a.ExtRef1 = b.ExtRef1 
                  AND a.SedolRef = b.SedolRef 
                  AND a.ValLatest = b.ValLatest 
                  AND a.Totunits = b.Totunits 
                  AND a.FundsOrCash = b.FundsOrCash )

5 个答案:

答案 0 :(得分:2)

比较很多列时,SELECT INTERSECT和SELECT EXCEPT命令可以为您节省很多精力:

INSERT dbo.coftReconcilliationMatches
   (Rec_PK, ExtRef1, SedolRef, ValLatest, Totunits, FundsOrCash, MatchOrNoMatch)
 select Rec_PK, ExtRef1, SedolRef, ValLatest, Totunits, FundsOrCash, 'Match'
  from dbo.coftReconciliationFileInfo
 intersect select Rec_PK, ExtRef1, SedolRef, ValLatest, Totunits, FundsOrCash, 'Match'
  from dbo.coftPreReconciliationFileInfo

(检查拼写错误!)

如果您是动态创建表格(我不建议这样做),您可以使用SELECT INTO

答案 1 :(得分:0)

INSERT INTO [table] ([col1], [col2]) SELECT colx, ...

答案 2 :(得分:0)

答案 3 :(得分:0)

尝试类似:

INSERT INTO <your table> (<list of columns>)
SELECT <list of columns from select>, '<the additional column>' FROM dbo.coftReconciliationFileInfo AS a 
WHERE EXISTS(SELECT * FROM dbo.coftPreReconciliationInfo AS b 
WHERE a.Rec_PK = b.Rec_PK AND a.ExtRef1 = b.ExtRef1 AND a.SedolRef = b.SedolRef AND     a.ValLatest = b.ValLatest AND a.Totunits = b.Totunits AND a.FundsOrCash = b.FundsOrCash )

另见http://www.1keydata.com/sql/sqlinsert.html

答案 4 :(得分:0)

你需要这样做:

INSERT INTO Table (column1, column2..)
(SELECT column1, column2 .... 
  FROM dbo.coftReconciliationFileInfo AS a 
 WHERE EXISTS (SELECT * 
                 FROM dbo.coftPreReconciliationInfo AS b 
                WHERE a.Rec_PK = b.Rec_PK 
                  AND a.ExtRef1 = b.ExtRef1 
                  AND a.SedolRef = b.SedolRef 
                  AND a.ValLatest = b.ValLatest 
                  AND a.Totunits = b.Totunits 
                  AND a.FundsOrCash = b.FundsOrCash ))