I have realized that there are 2 ways of running a dynamic string on a different database:
the first one is the following:
declare @sql nvarchar(max)
set @sql = 'select 1'
exec MyDatabase.sp_execute @sql
the second one would be:
declare @sql nvarchar(max)
set @sql = 'Use MyDatabase
select 1'
exec sp_execute @sql
Can anyone point the differences between the 2 approaches? If one is better than the other and why?
Useset’s the database context for the current session, while in yourexecstatement, you’re telling it what database to use for only the statement. After theexecstatement, your session’s database context won’t have change to what you ran.So, in the case of your example, there’s no functional difference. In the more general sense, there is a rather large one.
You can also do this:
That will pull data from another database than your context. You can use this to join data between databases, as well, just like you do normal joins.