You can try this at home!
I use this udf to capture the number of cores available when my stored procedure runs in cloud. But, since I develop against my local on-prem database, I coded it to return a -1 when it's not running in the cloud. Here's the whole thing:
CREATE OR ALTER FUNCTION dbo.sfnGetCores()
RETURNS SMALLINT
AS
BEGIN
DECLARE @Result SMALLINT = NULL
IF OBJECT_ID('sys.dm_db_resource_stats') IS NOT NULL
SELECT @Result = cpu_limit FROM sys.dm_db_resource_stats WITH (NOLOCK) ORDER BY end_time DESC
IF @Result IS NULL SET @Result = -1
RETURN @Result
END
GO
Now, when I run this
SELECT dbo.sfnGetCores() AS Cores
in SSMS against a SQL Server 2017 compatibility level database, it always works. When I change the compatibility level to 2019 or 2022, it works sometimes and fails sometimes. If it works, I add few spaces, or few empty lines, then run again. It will fail once - then start working again. I get a similar "variety" of working/failing when I embed this in a stored procedure.
I suspect the introduction of scalar udf inlining in 2019 may be related, but this line from the documented requirements says it should be excluded as an inline candidate.
"The UDF doesn't reference built-in views (such as OBJECT_ID) 4."
I suspect when it uses a cached plan, it doesn't fail. This:
SELECT dbo.sfnGetCores() AS Cores OPTION (RECOMPILE)
works consistently in 2017 and fails consistently in 2019 and 2022.