The function below will fails when I run it the first time with the following error:
8124 (Multiple columns are specified in an aggregated expression containing an outer reference.)
The second time I run it it runs normally.
If I remove *DATEDIFF(D, e.FRADATO , @til)
it’s no problem.
ALTER FUNCTION [dbo].[fnc_2019_test]
(@m_id INT, @fra DATE, @til DATE)
RETURNS INT
AS
BEGIN
RETURN
(SELECT
SUM(ISNULL(e.FORBRUK, 0) * DATEDIFF(D, e.FRADATO, @til))
FROM
dbo.mlr_eos_avl e
WHERE
e.MÅLER_ID = @m_id
AND @fra < e.DATO
AND DATEADD(D, -1, @til) >= e.FRADATO)
END
This function works in SQL Server 2008 R2 and SQL Server 2016 without any problem.
SQL Server 2019 is still in CTP and this is a new feature. If you have found a bug in it you should report it to Microsoft so it is fixed before release (done for you here). (Edit this bug has now been marked as fixed, presumably in CU6)
On previous versions if you try and manually inline it you will see the same error (as in the cut down example below). This is because of the limitation discussed here.
WITH T(m_id,fra, til) AS
(
SELECT 1, GETDATE(), GETDATE()
)
SELECT *
FROM T
CROSS APPLY
(SELECT
SUM(DATEDIFF(D, e.FRADATO, til))
FROM
dbo.mlr_eos_avl e
) CA(result)
Until this inline case is fixed by Microsoft you can use
WITH INLINE = OFF
in the scalar UDF definition to disable inlining of the UDF