What I'd like to do is evaluate a SQL expression like the following:
IF HAS_DBACCESS('ExampleDB') = 1
BEGIN
USE ExampleDB
--Other stuff
END
As per this query, it should only perform actions relating to ExampleDB should the user executing this query have access to ExampleDB.
When I run this query as a user without access to this DB, I get the following error message:
The server principal "MY_USERNAME" is not able to access the database "ExampleDB" under the current security context.
This is odd to me. I do not have access to ExampleDB. Therefore, HAS_DBACCESS('ExampleDB') evaluates to 0. I've confirmed this by selecting its value. In fact, if I replace the USE ExampleDB with anything other than a USE statement (for example, SELECT 'Test'), it doesn't evaluate, which is correct behaviour.
For some reason, it's trying to evaluate access for USE ExampleDB before even checking the condition. Is this expected behaviour? And if so, is there any way around this?