No, you cannot do USE on a remote database.
But rather than using USE, you can do:
SELECT @sp_executesql = @mydb.sys.sp_executesql
EXEC @sp_executesql N'SELECT * FROM mytable'
This works, because:
- You can give a variable name to EXEC for which stored procedure to use.
- sp_executesql will execute in the context of the database from which it was invoked. Which will be the database in @mydb in this case.
And you can also do:
SELECT @sp_executesql = @linkedserver.mydb.sys.sp_executesql
EXEC @sp_executesql N'SELECT * FROM mytable'
One obvious restriction: the remote data source must be another SQL Server instance.