How can I get the database name from which stored procedure is called?

1.9k views Asked by At

See comments in code.

use master
go

create database db1
create database db2
go

-------------------------------
use db2
go

create procedure proc2
as begin
    -- how I can figure out that this proc2 is called 
    -- 1. from proc1 which is contained in the db1 (case N1)
    -- 2. or from context of db1 (case N2)
    select DB_NAME()
end
go

-------------------------------
use db1
go

create procedure proc1
as begin
    exec db2.dbo.proc2
end
go

select DB_NAME();

-- case N1
exec dbo.proc1;

-- case N2
exec db2.dbo.proc2;


-------------------------------
use master
go

drop database db1
drop database db2

Output

db1
db2
db2
2

There are 2 answers

3
r.net On BEST ANSWER

If I remember correctly, I don't think it is possible.

There is a work-around, you can add an extra input parameter in proc2 and pass the information to it.

0
Granger On

Here's the original script, but with a quick change to proc2 based on my answer over here. (Note that sys.dm_tran_locks requires 'VIEW SERVER STATE' permissions to use.)

Output

db1
db1
db1

Script

use master
go

create database db1
create database db2
go

-------------------------------
use db2
go

create procedure proc2
as begin
    DECLARE @result nvarchar(128);
    SELECT TOP 1 @result = DB_NAME(resource_database_id) 
        FROM sys.dm_tran_locks 
        WHERE request_session_id = @@SPID 
            AND resource_type = 'DATABASE' 
            AND request_owner_type = 'SHARED_TRANSACTION_WORKSPACE' 
        ORDER BY IIF(resource_database_id != DB_ID(), 0, 1);
    SELECT @result;
end
go

-------------------------------
use db1
go

create procedure proc1
as begin
    exec db2.dbo.proc2
end
go

select DB_NAME();

-- case N1
exec dbo.proc1;

-- case N2
exec db2.dbo.proc2;


-------------------------------
use master
go

drop database db1
drop database db2