Monday, March 26, 2012

How to determine sp caller current database?

When executing a stored procedure that is defined in another database, as:

USE db1;

EXEC db2.dbo.sproc;

Is there a way in the stored procedure "sproc" to determine that the caller made the call from db1?

If nothing else, you can use CONTEXT_INFO to retain that information.

To call the stored procedure you can do something like:

Code Snippet

USE db1;

declare @.binVar varbinary(128)
set @.binVar = convert(varbinary(128), 'db1')
set context_info @.binVar

EXEC db2.dbo.sproc;

and to fetch the information from within the stored procedure you can use something like:

Code Snippet

convert(varchar(128), context_info())

( This is assuming that db_name() is not working for you. )

sql

No comments:

Post a Comment