title: SQL Conditional Union Based On Parameter
body: <p>I have this query which takes in 3 parameters, <code>StrParameter1</code> being the one which is key to what I'm trying to accomplish.</p>
  
  <pre><code>SELECT  ai.strName,
  ai.strId,
  ai.lngBKey,
  ci.strFormattedId,
  ci.lngAKey,
  ts.dtmPeriod,
  ts.strT2Type,
  ts.strImpact,
  ts.curAmount,
  ts.curBalance 
  
  FROM    TBlCInfo ci,
  tblAInfo ai,
  tblTStage ts 
  
  WHERE   ci.lngAKey    =  ai.lngAKey 
  AND     ai.lngBKey    =  ts.lngBKey 
  AND     ts.lngVersion    =  0 
  AND     ts.blnReversed   =  0 
  AND     ai.strType   =   @StrParameter1
  AND     ts.dtmPeriod  &gt;= @DtmParameter2
  AND     ts.dtmPeriod  &lt;= @DtmParameter3
  </code></pre>
  
  <p>I'd like to union this query with another, but only if StrParameter1 equals let's say, "AAAA". Otherwise, I only want the top portion of the query to fire. There's like 30 other circumstances where I would not need the union, but only 1 where it's needed. </p>
  
  <pre><code>Query 1
  
  If StrParameter1 = 'AAAA' Then
      UNION
            QUERY 2
  </code></pre>