I have a SQL Server agent job that runs daily, and the first step is to check that a required process finished on another server. This check is done through a function, which I'm calling through openquery and a linked server. The job also uses
a bit of dynamic sql to add needed parameters:
set @command = 'SELECT @result = [ReturnValue] from openquery([amlidw],''select [amlidw].[dbo].[process_control_checkrun](''''' + @parent_process_key + ''''',''''' + @child_process_key + ''''',' + ISNULL('''''' + @parent_process_key2+ '''''','default') + ',default) AS [ReturnValue]'') '
exec sp_executesql @command,N'@result int output',@result=@result output
This function will run correctly, and return the correct results for several days. Then it will start returning 0 when the correct value is 1. I have even gone so far as to use SQL Server Profiler to check the query being sent, then run it myself on the target server. In this case it correctly returns 1 on the target server, but the openquery version returns 0.
The only way I can get the correct results again is to make a trivial change to the query. For instance, I can change the name of the return value to ReturnValueTest, and the function will return correct results for several days. This would suggest that the return value is somehow being cached until the text changes.
What is going on here? Is there a way to ensure that the results will be returned correctly across servers? I could experiment with different way to call the function, but not knowing the cause, I don't exactly know what to do differently.
Both severs in this scenario are SQL Server 2017, and the linked server provider is SQLOLEDB. Thanks for any insight this group may have. This one really has me stumped.