Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Assume that I have three databases - dbOne, dbTwo and dbThree. If I have a stored procedure in DbThree, how can I get it to return the name of the database where the original command was executed?

Using the following only gives the database where the procedure is held:

CREATE PROCEDURE GetDatabaseName
AS
SET NOCOUNT ON
BEGIN
SELECT DB_Name()  -- SELECT DB_Name(dbid) returns the same result.
END


So calling it from any database returns dbThree whereas I need it to return dbOne, dbTwo etc.
Posted
Updated 30-Mar-15 0:38am
v2

1 solution

Thats because the SP is running in dbThree - when you use
SQL
EXEC [dbThree].[dbo].GetDatabaseName
You are effectively issuing a USE dbThree command for the duration of the EXEC
If you want the "original" database name, then you need to add the same procedure in all the DBs, and remove any qualification when you EXEC it.
 
Share this answer
 
Comments
lmaycock 30-Mar-15 7:18am    
So essentially there's no way of doing it in this way... annoying, but as suspected! Thanks.
OriginalGriff 30-Mar-15 7:24am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900