title: If Exists allowing a null value through
body: <p>I have a catch script that is meant to pick up when a sum comes out with a null value and insert a 0, which works fine on one query but not my current one, if I break down what code I am using</p>
  
  <pre><code>Declare @Period int = 5
  SELECT A.MATTER_CODE,DATEPART(month,A.DATE_OPENED) As DateOpened,B.DEPTNAME,B.DEPTCODE 
  INTO #TmpPREVYTD
  FROM MATTER A
  LEFT JOIN DEPT_MASTER B on A.DEPT_CODE = B.DEPTCODE
  WHERE A.date_opened between DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, -1, GETDATE())), 120) and 
  DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GETDATE())), 120)
  ORDER BY DATE_OPENED
  </code></pre>
  
  <p>This pushes out the data I require for the query in the correct year and month</p>
  
  <pre><code>SELECT COUNT(*) As 'Fin',Dateopened Into #TmpPFin FROM #TmpPREVYTD where DEPTCODE = 'FIN' GROUP BY 
  DATEOPENED
  </code></pre>
  
  <p>This counts every time a job relating to Finance is in the raw data.</p>
  
  <pre><code>SELECT SUM(FIN)As Fin INTO #PFIN FROM #TmpPFIN WHERE Dateopened Between 5 and @Period
  </code></pre>
  
  <p>This then sums up all the months which relate to the required set months, so in this example I just want it to count May only, which has nothing in it, thus why it is pushing a null value.</p>
  
  <pre><code>If EXISTS(Select Fin from #PFIN) 
  GOTO TmpITD
  Else insert into #PFIN (Fin) Values( 0) 
  TmpITD:
  </code></pre>
  
  <p>Finally this is the catcher which should be finding the #PFin has a null value and inserting a 0, however what I think it is doing is going straight to TmpITD, as if I just run the insert statement it adds the 0.</p>
  
  <p>so currently if I run the entire statement I keep getting a null value which means the report in the end comes out blank.</p>
  
  <p>Am I missing something here as this exact same code works in other queries but not in this one, it would appear that perhaps it does exist somehow but with a null value, which has totally confused me.</p>
  
  <p>EDIT: If I add something to the end of TmpITD it pushes that out so I know for sure now that the problem is the if Exists thinks it does exist when it is actually Null</p>