如何获取调用存储过程的数据库名称?

时间:2013-08-21 20:47:30

标签: sql-server tsql stored-procedures sql-server-2012 executioncontext

请参阅代码中的注释。

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

输出

db1
db2
db2

2 个答案:

答案 0 :(得分:0)

如果我没记错的话,我认为不可能。

有一种解决方法,您可以在proc2中添加额外的输入参数并将信息传递给它。

答案 1 :(得分:0)

这是原始脚本,但是基于my answer over here快速更改为proc2。 (请注意,sys.dm_tran_locks要求具有“查看服务器状态”权限。)

输出

db1
db1
db1

脚本

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