title: SQL Server - Variable assignment using UNION
body: <p>I'm trying to assign a variable value using UNION ALL but i receive an error:</p>
  
  <blockquote>
    <p>Variable assignment is not allowed in a statement containing a top
    level UNION, INTERSECT or EXCEPT operator.</p>
  </blockquote>
  
  <p>How can I assign a value using UNION? Here is the sql that i'm trying to make:</p>
  
  <pre><code>SELECT @Totals = SUM(Quantity)      
    FROM ConsData A WITH(NOLOCK)      
  INNER JOIN #TmpData B ON B.DataId = A.DataId 
  INNER JOIN Data cp ON cp.DataId = A.DataId           
   WHERE A.Status = -1 AND cp.Date IS NOT NULL
  UNION ALL
  SELECT @Totals = cg.Total  
          FROM ConsDataGenerated cg
              INNER JOIN #TmpData B ON B.DataId = cg.DataId
              INNER JOIN Data cp ON cp.DataId = B.DataId
          WHERE cp.Date IS NULL   
  </code></pre>