SQL插入不存在加载所有记录而不是1

时间:2014-02-21 10:14:23

标签: sql sql-server

我正在测试一个概念,但在理解为什么这不起作用时遇到了问题。我知道有解决方法,但想知道为什么这不起作用。

表格中有4行名为#test,所有关键字都关闭10002677818269286.从表格中选择时,如果表格中没有,则表示加载一行。我希望它是插入第一条记录并拒绝其余记录。但是所有人都得到了加载。这是代码

INSERT INTO #final_phone_t
(batch_id, ExternalID, CompanyCode, SeqNumber, PhoneType, AreaCode, Number,Num2)
SELECT
    tp.batch_id, tp.ExternalID, tp.CompanyCode, tp.SeqNumber, tp.PhoneType,
    tp.AreaCode,tp.Number,
    CONVERT(varchar(7), tp.ExternalID) + RTRIM(tp.AreaCode) + RTRIM(tp.Number)
FROM #test tp
WHERE not EXISTS(    
    SELECT 1   
    FROM #final_phone_t fp
    WHERE 10002677818269286
   = Num2
)   
ORDER BY tp.ExternalID, tp.PhoneType ASC

2 个答案:

答案 0 :(得分:1)

EXISTS关键字仅测试指定条件是否存在行。正如评论中所指出的,您需要限制外部SELECT查询中的行集。由于您只希望插入第一行,因此可以添加TOP 1以将查询结果限制为1行。查询如下:

INSERT INTO #final_phone_t 
            (batch_id, 
             externalid, 
             companycode, 
             seqnumber, 
             phonetype, 
             areacode, 
             number, 
             num2) 
SELECT TOP 1 tp.batch_id, 
             tp.externalid, 
             tp.companycode, 
             tp.seqnumber, 
             tp.phonetype, 
             tp.areacode, 
             tp.number, 
             CONVERT(VARCHAR(7), tp.externalid) 
             + Rtrim(tp.areacode) + Rtrim(tp.number) 
FROM   #test tp 
WHERE  NOT EXISTS(SELECT 1 
                  FROM   #final_phone_t fp 
                  WHERE  num2 = 10002677818269286 
                 --Column name on the left, literal on the right 
                 ) 
ORDER  BY tp.externalid, 
          tp.phonetype ASC 

答案 1 :(得分:1)

INSERT INTO #final_phone_t
  (batch_id, ExternalID, CompanyCode, SeqNumber, PhoneType, AreaCode, Number,Num2)
SELECT Top 1//but here you are selecting all records this is the actual statement which is inserting into DB so use Select Top 1 here as well.
  tp.batch_id, tp.ExternalID, tp.CompanyCode, tp.SeqNumber, tp.PhoneType,
  tp.AreaCode,tp.Number,
  CONVERT(varchar(7), tp.ExternalID) + RTRIM(tp.AreaCode) + RTRIM(tp.Number)
FROM #test tp
WHERE not EXISTS(    
  SELECT 1  //Here for comparison you are selecting only one record.  
  FROM #final_phone_t fp
  WHERE 10002677818269286
  = Num2
)   
ORDER BY tp.ExternalID, tp.PhoneType ASC