title: Using "UNION" with "IF EXISTS"
body: <p>I have the following problem on SQL Server 2008 R2, I'm trying to use an <code>IF EXISTS</code> clause on a group of <code>UNION</code> and I'm getting an error.</p>
  
  <p>If I run the query separated, they run without errors, but if I try to run them with an UNION, it gave me the error:</p>
  
  <blockquote>
    <p>Msg 156, Level 15, State 1, Line 9<br>
    Incorrect syntax near the keyword 'IF'.</p>
  </blockquote>
  
  <pre class="lang-sql prettyprint-override"><code>SELECT
      '1.5.2- Customers' as INPUT,
      count (distinct ID) as Z,
      PRO_DATE,
      Month(PRO_DATE) as P_MONTH,
      Year(PRO_DATE) as P_YEAR
  FROM
      [BASE]
  WHERE
      BASE.CAT_CUSTO = 'EMPLO' and
      BASE.ESTAT = 'EX'
  group by
      PRO_DATE
  
  UNION 
  
  IF  EXISTS (
      SELECT
          '1.6- OTHER CUSTOMERS' as INPUT,
          count (distinct ID)  as Z,
          PRO_DATE,
          Month(PRO_DATE) as P_MONTH,
          Year(PRO_DATE) as P_YEAR
      FROM
          [BASE]
      WHERE
          BASE.CAT_CUSTO &lt;&gt; 'EMPLO'
      group by
          PRO_DATE
  )  begin
  SELECT
          '1.6- OTHER CUSTOMERS' as INPUT,
          count (distinct ID)  as Z,
          PRO_DATE,
          Month(PRO_DATE) as P_MONTH,
          Year(PRO_DATE) as P_YEAR
      FROM
          [BASE]
      WHERE
          BASE.CAT_CUSTO &lt;&gt; 'EMPLO'
      group by
          PRO_DATE
  
   end
  ELSE
      SELECT TOP 1
          '1.6- OTHER CUSTOMERS' as INPUT,
          0 as Z,
          PRO_DATE,
          Month(PRO_DATE) as P_MONTH,
          Year(PRO_DATE) as P_YEAR
      FROM
          [BASE]
  </code></pre>