4

这是在另一个数据库的上下文中从一个数据库调用存储过程时与上下文相关的问题。

假设我在以下位置创建了一个程序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

现在,我想从另一个过程中调用该过程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

我的问题是:当MainDB.dbo.sp_mainproc从内部调用时,在AuxDB.dbo.sp_action其中搜索dbo.xUser使用的表sp_mainproc。是被MainDB.dbo.xUser考虑的,还是被AuxDB.dbo.xUser搜索的?

谢谢,彼得

4

1 回答 1

5

procs 是编译的,所以它会引用dbo.sp_mainproc存在于同一个数据库中的对象,因为当 proc 被创建时,它只引用dbo.xUser,它没有数据库名称部分

(即无论从哪个数据库调用 proc 都MainDB.dbo.sp_mainproc将使用)。MainDB.dbo.xUser

于 2012-08-31T13:09:25.130 回答