This is a question related to the context when calling a stored procedure from one database in the context of another database.
Say I have a procedure created in the MainDB:
USE MainDB;
GO
CREATE PROCEDURE dbo.sp_mainproc
@Login nvarchar(50),
@Error INT OUTPUT
AS
BEGIN
-- many details left out...
-- Login as string must be captured in the xUser table to get
-- the personal settings for the user...
SET @_user_id = ( SELECT dbo.xUser.user_id
FROM dbo.xUser
WHERE dbo.xUser.login = @Login );
IF( @_user_id IS NULL )
BEGIN
-- The user with the given @Login is not present. Indicate the failure.
SET @Error = 2
RETURN (1)
END
-- Do something in the MainDB. Here the main reason for calling
-- the stored procedure is implemented.
-- Indicate the success when finishing.
SET @Error = 0
RETURN (0)
END
GO
Now, I want to call the procedure from another procedure in the AuxDB:
USE AuxDB;
GO
CREATE PROCEDURE dbo.sp_action
AS
BEGIN
-- Call the MainDB.dbo.sp_mainproc to do the action in the MainDB.
-- The login name must be passed, and possible error must be checked.
DECLARE @error INT
DECLARE @retcode INT
EXEC @retcode = MainDB.dbo.sp_mainproc
N'the_user',
@error OUTPUT
IF (@retcode <> 0)
BEGIN
-- Here the error must be signalized.
RETURN 1
END
-- Everything OK, let's continue...
RETURN 0
END
GO
My question is: When the MainDB.dbo.sp_mainproc is called from within AuxDB.dbo.sp_action, where the dbo.xUser table used in the sp_mainproc is searched for. Is the MainDB.dbo.xUser considered, or is the AuxDB.dbo.xUser searched for?
Thanks,
Petr
Procs are compiled, so it will refer to the object in the same database in which the
dbo.sp_mainprocexists, because when the proc was created, it refers only todbo.xUser, which doesn’t have a database name part(i.e.
MainDB.dbo.sp_mainprocwill useMainDB.dbo.xUserirrespective of which database that the proc is called from).