在一个表中插入IF记录EXISTS而在其他表中不插入EXISTS

时间:2015-01-19 18:47:23

标签: sql sql-server tsql if-statement

IF EXISTS

的问题

我有两张桌子

create table #Table1 
(
     DateID date,  Shop int, MAC int, Stock int, Transit int 
)

INSERT INTO #Table1  values ('01.01.2014', 1, 2, 2,3)
INSERT INTO #Table1  values ('01.04.2014', 1, 2, 2,3)`

create table #Table2
(
    DateID date,  Shop int, MAC int, OnHand int 
)

INSERT INTO #Table2  values ('01.01.2014', 1, 2, 2)
INSERT INTO #Table2  values ('01.01.2014', 2, 3, 1)
INSERT INTO #Table2  values ('01.01.2014', 3, 1, 4)
INSERT INTO #Table2  values ('01.02.2014', 1, 2, 5)

如果表1中的DateID,Shop,MAC不存在,我需要插入表1中,但是表2中存在

我有这个陈述

DECLARE @Date date =  '01.02.2014'

IF EXISTS (SELECT a.DateID, a.Shop, a.MAC 
           FROM #Table1 a  
           INNER JOIN #Table2 b ON a.Shop = b.Shop  
                                 AND a.MAC = b.MAC 
                                 AND a.DateID = b.DateID  
           WHERE a.DateID = @Date) 
   INSERT INTO #Table1 (DateID, Shop, MAC, Stock)
      select 
          @Date, a.Shop, a.MAC , sum (OnHand)
      from 
          #Table2 a
      where 
          DateID <= @Date
      group by  
          a.Shop, a.MAC 
      order by 
          1 
other IF
else

它正在工作,但因为它有

IF  EXISTS

如果我正在使用

,它总是如此
IF NOT EXISTS

它始终是假的,这部分永远不会执行。

enter image description here enter image description here

请任何帮助!

3 个答案:

答案 0 :(得分:3)

您可以在sql语句而不是if语句中执行此操作:

insert into #Table1
(DateID, Shop, MAC, Stock)

select  @Date, a.Shop, a.MAC , sum(OnHand)
from  #Table2 a
left join #Table1 b
    ON a.Shop = b.Shop  
    AND a.MAC = b.MAC 
    AND a.DateID = b.DateID  
where b.Shop is null
group by  a.Shop, a.MAC 
order by 1 

如果您需要IF stmt - 请执行以下操作:

set @RowsToInsert = 0

select @RowsToInsert = count(*)  
  from #Table2 a 
  left join #Table1 b 
  ON a.Shop = b.Shop AND a.MAC = b.MAC AND a.DateID = b.DateID 
where b.Shop is null 

IF @RowsToInsert > 0 ...  you will need to put insert logic here

IF @RowsToInsert = 0 ...  no rows are missing, put update or other logic here

答案 1 :(得分:1)

如果您想使用EXISTS,那么这可能会有效:

INSERT INTO #Table1 (DateID, Shop, MAC, Stock)
SELECT  @Date, 
        A.Shop, 
        A.MAC , 
        SUM (OnHand)
FROM    #Table2 A
WHERE   NOT EXISTS
        (
         SELECT 1
         FROM   #Table1 B
         WHERE  A.Shop   = B.Shop AND 
                A.MAC    = B.MAC AND 
                A.DateID = B.DateID  
        ) 
        AND
        A.DateID <= @Date
GROUP BY 
        A.Shop, 
        A.MAC 

答案 2 :(得分:0)

我通过创建NONCLUSTERED INDEX并设置IGNORE_DUP_KEY = ON

来修复它
create table #Table1  (
     DateID date,  Shop int, MAC int, Stock int, Transit int  ) 
CREATE UNIQUE NONCLUSTERED INDEX IX_RecvID ON #F_STOCK (DateID,Shop ,MAC) WITH (IGNORE_DUP_KEY = ON)