I agree it's a bug. Here is a reproduction (I simplified the code somewhat). I'm running SQL 2019 CU15.
Use tempdb
go
-- Create table with 200 rows vith values from 1-200
Create Table dbo.InterfaceTraffic(In_Averagebps real);
go
;With cte As
(Select Cast(1 As real) As r
Union All
Select r+1. As r
From cte
Where r<200)
Insert dbo.InterfaceTraffic(In_Averagebps)
Select r
From cte
Option (Maxrecursion 300);
go
-- Create Function
Create Function dbo.SampleProc()
Returns real
As
BEGIN
DECLARE @ResultVar real
SELECT @ResultVar = MAX(In_Averagebps)
FROM (
SELECT TOP 95 PERCENT In_Averagebps
FROM dbo.InterfaceTraffic
ORDER BY In_Averagebps ASC
) AS AA
RETURN @ResultVar
END
go
-- Call to function returns incorrect result 95, should be 190
Declare @ReturnedResult real;
Select dbo.SampleProc() As BadResult
go
-- Executing same code outside of functions returns correct result 190
DECLARE @ResultVar real
SELECT @ResultVar = MAX(In_Averagebps)
FROM (
SELECT TOP 95 PERCENT In_Averagebps
FROM dbo.InterfaceTraffic
ORDER BY In_Averagebps ASC
) AS AA
Select @ResultVar As GoodResult
go
--Cleanup
Drop Function dbo.SampleProc;
go
Drop Table dbo.InterfaceTraffic;
Tom