Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Identify which database a stored proc has been called from

Status
Not open for further replies.

starsky51

MIS
Mar 11, 2002
91
I'm trying to write a stored procedure which can identify which database it has been called from. Using the following example:
Code:
USE database1
GO
CREATE PROC dbo.uspPrintDbName
AS
PRINT DB_NAME()
if I call it from a different database:
Code:
USE database2
GO
EXEC database1.dbo.uspPrintDbName
it would print the string 'database1'.

What I would like is for the stored proc to identify which context the EXEC statement was in when it was run. (In this example, 'database2'.)
Any ideas?
 
Guess the obvious would be to hard code it in the sp.

But then it would not be dynamic if you moved the sp to anouther db.

Simi
 
how about something like this

Code:
SELECT    name
FROM         master.dbo.sysprocesses p
inner join master.dbo.sysdatabases db
on p.dbid = db.dbid
where spid=@@spid
 
PWise. I had high hopes for your suggestion but, annoyingly, the dbid value gets updated when the session executes the sproc. I've had a hunt through some of the other sys tables, but none of them seem to hold the info I need.

It looks like I'll have to set up the sproc with an extra @dbname parameter and get the user to enter it manually.

Thanks to you both for your suggestions.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top