Cyberherbalist
Cyberherbalist

Reputation: 12319

How can a stored proc retrieve the name of the database it's running in?

I have a stored procedure which can be run in a number of databases, and the functioning of the stored procedure needs to vary slightly depending on the database. I've been all over books online and looked in the system tables to see if this might be somewhere in there, but so far no joy.

There's got to be someone here who just happens to know this, if it exists at all.

Upvotes: 0

Views: 68

Answers (2)

Remus Rusanu
Remus Rusanu

Reputation: 294297

A procedure always runs in the database it exists in. Invoking EXEC <dbfoo>..<procname> is exactly as swithing context to <dbfoo> then executing <procname>.

If you have multiple procedures, one in each DB, then you can either change the procedure accordingly on each DB or use DB_NAME() to get the current db.

Upvotes: 1

JP Alioto
JP Alioto

Reputation: 45117

SELECT db_name()

Should do it. Docs are here.

Upvotes: 5

Related Questions