title: SQL Function, Column as a variable
body: <p>new to SQL programming,
  I have this function which works well:</p>
  
  <pre><code>(
  @clientId AS int
  )
  RETURNS NVARCHAR(50)
  AS
  BEGIN
  declare @result nvarchar(50);
  declare @lastDate Date;
  declare @dateBefore Date;
  declare @count float;
  set @count = (select  MAX(A1c)-MIN(A1c) as change from
  (select A1c from 
  ( select top 2 * from vw_MasterView where clientId = @clientId order by vw_masterView.LastVisitDate desc  ) as vw
  group by A1c) as hh);
  RETURN @count
  end;
  </code></pre>
  
  <p>Since I will be repeating this function to calculate other columns from the MasterView; I would like to change A1c to a variable, as the following:</p>
  
  <pre><code>(
  @clientId AS int,
  @lab AS nvarchar(50)
  )
  RETURNS NVARCHAR(50)
  AS
  BEGIN
  declare @result nvarchar(50);
  declare @lastDate Date;
  declare @dateBefore Date;
  declare @count float;
  set @count = (select  MAX(@lab)-MIN(@lab) as change from
  (select @lab from 
  ( select top 2 * from vw_MasterView where clientId = @clientId order by vw_masterView.LastVisitDate desc  ) as vw
  group by @lab) as hh);
  RETURN @count
  end;
  </code></pre>
  
  <p>I got the following errors:</p>
  
  <pre><code>Msg 164, Level 15, State 1, Procedure fn_changeA1c, Line 22
  Each GROUP BY expression must contain at least one column that is not an outer reference.
  Msg 8155, Level 16, State 2, Procedure fn_changeA1c, Line 22
  No column name was specified for column 1 of 'hh'.
  </code></pre>
  
  <p>Thanks in advance.</p>