Sample Header Ad - 728x90

On SQL 2022, DECLARE statement causes evaluation of database availability

14 votes
2 answers
508 views
Ok, this is a head scratcher for us. Hopefully someone out there can shed some light. This behaviour is only occurring on SQL 2022 for us -- and not on 2016, 2017 or 2019. Let's say we have a database that is offline. We can execute this fine: IF 1=0 EXEC [An_Offline_DB].dbo.[Some_Stored_Proc] As you'd expect, there is no error, because it clearly is not going to try and execute the proc. However, if we add in a completely unrelated DECLARE statement like this: DECLARE @x int IF 1=0 EXEC [An_Offline_DB].dbo.[Some_Stored_Proc] GO on SQL 2022 we now get this error: Database 'An_Offline_DB' cannot be opened because it is offline. But on older versions of SQL it works fine. We have recreated this issue with readable secondaries in an AlwaysOn Availability Group, so the reason for the database being unavailable is not relevant. So it appears the presence of the DECLARE statement is causing a full evaluation of the script, but only for SQL 2022. One side note, is that if the database doesn't exist, we don't get an error: DECLARE @x int IF 1=0 EXEC [Does_Not_Exist].dbo.[Some_Stored_Proc] GO
Asked by Mike (892 rep)
Aug 8, 2025, 01:31 AM
Last activity: Aug 14, 2025, 07:51 AM