title: Setting a SQL local variable properly
body: <p><strong>I'm wondering if there is a way to have a local variable use the 'FROM' statement from a SELECT statement that is not declared in the 'SET' of the variable.
  I have the following example:</strong></p>
  <pre><code>DECLARE @IDNO int;
  DECLARE @ORDERQUANTITY int;
  
  SET @IDNO='1';  --TEST VALUE
  SET @ORDERQUANTITY=ISNULL(SUM(Table1.QUANTITY), 0);
  
  SELECT
  Table1.IdNo AS 'ID No',
  @ORDERQUANTITY AS 'Order Quantity'
  
  FROM Table1
  
  WHERE IdNo = @IDNO
  GROUP BY IdNo, QUANTITY
  </code></pre>
  <p>I have lots of columns which add columns together, and those columns that are added together are derived from statements like those in the <code>@ORDERQUANTITY</code> variable.</p>
  <p>So instead of having lengthy column definitions in my SELECT statement, I'd like to place things in variables to make the SELECT statement simpler</p>
  <p>e.g.</p>
  <p><code>SELECT @ORDERQUANTITY - @ORDERSCANCELLED AS 'Net Sold'</code></p>
  <p>The best way to approach this would be appreciated!</p>
  <p>(Using SQL Server)</p>