I have a SQL statement that I run against a large number of SQL Server instances in order to collect data about the service account. The SQL statement includes a management view that is not available in all versions of SQL Server, and when it's not available, I want it to return 'Data not available' rather than error out. This seems like it would be an easy case for try/catch or if/else, but it isn't. Instead, the SQL Server engine evaluates it and throws the 'Invalid object name' error before entering into the try/catch or if/else logic.
Examples:
-- Example 1
IF EXISTS (SELECT * FROM sys.dm_server_services) 
BEGIN
   SELECT * FROM sys.dm_server_services 
END
ELSE
BEGIN
    SELECT 'No Data'
END
-- Example 2
BEGIN
    BEGIN TRY
        SELECT * FROM sys.dm_server_services
    END TRY
    BEGIN CATCH
        SELECT  
            'No data available' as Service_Account
            ,ERROR_NUMBER() AS ErrorNumber  
             ,ERROR_MESSAGE() AS ErrorMessage;  
    END CATCH
END;
GO
In both cases, sys.dm_server_services gets a red squiggly line and an invalid object error when ran, instead of evaluating as false and then doing the second part of the logic.
Any tips?
 
     
     
     
     
    