Link to home
Create AccountLog in
Avatar of rhservan
rhservanFlag for United States of America

asked on

What determines the DBName where Use [DBName] is at Top of Stored procedure?

I have a stored procedure that has gone through table changes none of which are in the original Use [DBNAme] database.  

How do I best determine which database I need to point it to.  

Please explain why this matters as well.
ASKER CERTIFIED SOLUTION
Avatar of Ramesh Babu Vavilla
Ramesh Babu Vavilla
Flag of India image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Ephraim Wangoya
You need to point to the database that contains the tables otherwise you would get errors since the SP will not be able to access the tables, unless your queries specifically use the database name
eg
   select * from DB1.dbo.Table1

This is useful if you are mixing tables from different databases in which case I would prefer to change the db to master
USE [master]

For me its more of a maintenance issue, if my queries reference one database, then there is no need to change the active database to some other db
You better not create something in master-db, keep your stuff in your databases.

For objects in a SP it's best not to give db-name for objects that are in same db as the SP itself. Why? When you restore database with another name (*_test) then it does not point to the original db.

Objects of another db there you don't have much choice but referencing them with the specific db-name. It's better as dynamic sql.
If your SP is only referencing objects of your other database then it's better to create that procedure in that other database. But you still can cover it for the caller.

(short version
GO
use db1
GO
Create procedure dbo.proc1
as begin
  select * from dbo.table1
end,
GO
use db2
GO
create procedure dbo.proc1
as
begin
  -- Call procedure from other database
  exec db1.dbo.Proc1
end;
GO

Open in new window


And then if you execute dbo.proc1 in db2 it is only a cover that executes the dbo.proc1 from db1.
Normally it goes to master. because always master as default  database.
You question not answered?