I inherited a project where each ‘customer’ has its own database. There are hundreds of databases. Stored procedures are currently not being used.
What are the best practices for consuming data here? Do I keep my stored procedures in the “master” database and use dynamic SQL to muck with data? It seems like there should be a much better way. I don’t want to have a job running to push stored procedures around hundreds of DBs to keep all the stored procedures in sync.
This dynamic SQL is working, but I want a better way.
CREATE PROCEDURE [Users_SELECT]
@DataBase nvarchar(20),
@UserID uniqueidentifier
AS
BEGIN
DECLARE @sql nvarchar(max)
SET @sql = ''
SET @sql += 'SELECT * FROM ' + @DataBase + '.dbo.Users u '
SET @sql += 'WHERE u.UserID=@UserID '
EXEC sp_executesql @sql, N'@UserID uniqueidentifier', @UserID
END
I tried EXEC sp_executesql 'USE ' + @DataBase + '; GO' then running a SELECT but I couldn’t get that working.
I figured it out. This will probably make SQL experts extremely mad, but I’m happy with the solution.
I created my stored procedures in ‘master’. I know this is usually a no-no. I then used
to mark each sproc as a system object. This way they can be called while under a different context. I can then do this:
and it will run in the context of the DataBase200 db, without having to actually deploy the sproc to that database. It is working great so far. Remember that you have to prefix your stored procedures names with
sp_in order for them to be recognized as system objects.I hope this helps someone.