rhservan
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.
How do I best determine which database I need to point it to.
Please explain why this matters as well.
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
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.
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
And then if you execute dbo.proc1 in db2 it is only a cover that executes the dbo.proc1 from db1.
(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
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?
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