在sql中使用if exists语句的问题

时间:2014-05-21 17:55:10

标签: sql sql-server tsql

我有2个表,一个称为TEMP,另一个称为MAIN。所以我要做的就是检查TEMP表中的所有记录是否都在MAIN表中。逻辑应该是来自临时表的所有记录也必须在主表中但是当我在这里运行sql查询时;它没有给我任何记录,我知道临时表中主表中缺少记录。我在这做错了什么?

IF EXISTS(SELECT DISTINCT GRP_NM
                 ,GRP_VAL 
          FROM TEMP 
          WHERE GRP_NM + GRP_VAL NOT IN (SELECT GRP_NM + GRP_VAL FROM  MAIN)
         )
  BEGIN 
   INSERT INTO  MAIN(GRP_NM, GRP_VAL )     
   SELECT GRP_NM
        ,GRP_VAL
  FROM  MAIN  
  WHERE GRP_NM + GRP_VAL NOT IN (SELECT GRP_NM + GRP_VAL FROM  MAIN)

  END

4 个答案:

答案 0 :(得分:3)

尝试

INSERT INTO  MAIN (GRP_NM, GRP_VAL)     
SELECT  GRP_NM, GRP_VAL 
FROM    dbo.MAIN m 
WHERE   NOT EXISTS 
(
    SELECT  * 
    FROM    dbo.TEMP t
    WHERE   t.GRP_NM = m.GRP_NM 
    AND     t.GRP_VAL = m.GRP_VAL 
)

注意:当子查询返回NULL时,由于NOT IN行为而不是NOT EXISTS使用NOT IN (subquery)

SELECT  'No, no, no' AS ColA
FROM    (SELECT 1) x(y)
WHERE   1 NOT IN 
(
    SELECT 2
    UNION ALL 
    SELECT NULL
)

SELECT  'Yep' AS ColB
FROM    (SELECT 1) x(y)
WHERE   NOT EXISTS
(
    SELECT  *
    FROM 
    (
        SELECT 2
        UNION ALL 
        SELECT NULL
    ) a(b)
    WHERE a.b = x.y
)

结果:

ColA
----------

(0 row(s) affected)

ColB
----
Yep

(1 row(s) affected)

答案 1 :(得分:2)

INSERT INTO  MAIN(GRP_NM, GRP_VAL )     
SELECT GRP_NM, GRP_VAL 
FROM  TEMP  
WHERE NOT EXISTS (SELECT 1 
                 FROM  MAIN
                 WHERE GRP_NM  = TEMP.GRP_NM
                 AND   GRP_VAL = TEMP.GRP_VAL )

答案 2 :(得分:2)

我怀疑你的问题与NULL有关。如果任一表中的GRP_NM或GRP_VAL都为空,则GRP_NM + GRP_VAL将为null,并且您的IN和EXISTS语句将完全混淆。

无论如何,试试这个:

INSERT MAIN (GRP_NM, GRP_VAL)
 select GRP_NM, GRP_VAL
  from TEMP
 except select GRP_NM, GRP_VAL
  from MAIN

答案 3 :(得分:1)

在代码的第二部分中,您尝试从同一个表MAIN(而不是TEMP)插入值。也许只是错字。 试试这样:

IF EXISTS(SELECT DISTINCT GRP_NM, GRP_VAL FROM TEMP WHERE GRP_NM + GRP_VAL NOT IN (SELECT GRP_NM      + GRP_VAL FROM  MAIN))
   BEGIN 
INSERT INTO  MAIN(GRP_NM, GRP_VAL )     
SELECT GRP_NM, GRP_VAL FROM  TEMP 
WHERE GRP_NM + GRP_VAL NOT IN (SELECT GRP_NM + GRP_VAL FROM  MAIN)

END