In a single SQL Server instance, I have the following databases:
- Headquarters
- Branch001
- Branch002
- Branch003
…
- Branchnnn
In each Branch DB is a procedure called usp_ComputeDailySales that does some computation and writes daily sales figures to the Headquarters DB. How do I write a single stored procedure in the Headquarters DB to execute usp_ComputeDailySales in all Branch DBs?
I could write something like the code below but I think this is not the way to go.
USE Branch001
EXEC usp_ComputeDailySales
USE Branch002
EXEC usp_ComputeDailySales
...
I wanted some way to execute the procedure for all Branch DBs all at the same time.
This is not dynamic SQL, but relies on something like deferred name resolution.
EXECUTE, see
@module_name_varparameterEdit, after KM’s comment
Yes, there is a difference but I’ll clarify:
EXEC (@SQL) means @SQL could be ‘
SELECT * FROM foo‘ OR ‘DELETE User WHERE 1=1';.)EXEC @SQL means @SQL is an object name. So I should have used @Obj
So, you could do this:
It avoids deferred name resolution errors. When the batch/proc is compiled, there is no error if dbo.uspCustomHook does not exist.
I’ve not used the technique since SQL 2000, and I don’t know if SQL 2005 (statement level recompilation) is clever enough to work out if @Obj should be be run because it does not exist so it does not try to compile the EXEC statement…
It’s also useful for cross database, same instance queries. You can configure prd-prod, dev-dev etc without relying on linked servers or hard coded databases names.