so I have a sproc in a db.. lets call this db A. This db makes use of tables (t1, t2) in another db. Lets call this db B.
okay, so the way i call it right now is: A.dbo.My_Proc but i get another error:
Invalid object name ‘dbo.t1’.
so how i tried supplying a parameter. In my Sproc i do, select * from @dbname.dbo.t1
however that results in an error. I can’t put the sproc in db B.
While it is sufficient to hardcode it (if there is a way), db B changes every year, so it would be nice to “supply” a database.
I tried using use B; go but it gives me error saying can’t have that in a sproc.
You could create a synonym:
EDIT: I see now that the synonym is needed for the table, not the proc. Got them switched. So you could create a synonym in database A for the table in database B:
Then your procedure in A could simply say:
Without having to manually supply the database name at all, the query knows (based on the synonym) to get the data from the table in database B. When the database B changes to C, you can simply:
If you used “real” database names in your narrative as opposed to arbitrary A/B names, it might lead to easier comprehension. Just a suggestion. 🙂
/EDIT
The other option is to pass in the database name and construct via dynamic SQL. E.g. instead of select * from @dbname.dbo.t1 (which will never work), you could do:
But if this other database name really only changes once a year, I suggest that the synonym route is better overall.