title: Unable to return top record in a T-SQL scalar function
body: <p>Here's my function which is supposed to return the top row of the record:</p>
  
  <pre><code>ALTER FUNCTION [dbo].[fn_PAT_LastTS] 
  (
      -- Add the parameters for the function here
      @PATcode varchar(50)
  )
  RETURNS datetime
  AS
  BEGIN
      -- Declare the return variable here
      DECLARE @lastTS datetime
  
      -- Add the T-SQL statements to compute the return value here
      SET @lastTS = (select top 1 tsdate from timesheet where pat = @PATcode order by tsdate desc)
  
      -- Return the result of the function
      RETURN @lastTS
  
  END
  </code></pre>
  
  <p>For some reason, it always returns all records instead of the top one. Does 'Top' work at all within T-SQL scalar function?</p>
  
  <p>Edit 1: this is how I call the function.</p>
  
  <pre><code>select dbo.fn_PAT_LastTS('ZZ793843') from timesheet
  </code></pre>
  
  <p>Edit: added the picture of returned data which showed multiple rows instead of the top 1.<img src="https://i.stack.imgur.com/INXcx.png" alt="enter image description here"></p>