从当前数据库中的另一个数据库运行存储过程

时间:2015-05-14 08:11:58

标签: sql-server-2008 stored-procedures

我有一个shared数据库和多个client数据库。数据存储在client数据库中。我们想在shared数据库中创建一组主存储过程,并从client数据库执行它们。鉴于以下内容:

use shared;
go
create procedure GetInvoices as
  print db_name() ' <- current database'
  select * from invoices
go

use client1;
create table invoices(...columns...)
exec shared.dbo.GetInvoices

这会返回以下错误:

shared <- current database
Msg 208, Level 16, State 1, Procedure GetInvoices, Line 3
Invalid object name 'invoices'.

如果没有使用动态SQL,我如何在shared client1中运行存储过程,以便它在client1中执行,从而可以访问所有client1中的表格?

3 个答案:

答案 0 :(得分:1)

您可以在master数据库的上下文中运行client1数据库中定义的存储过程,并查看所有client1数据库表不使用动态SQL ,但它使用 undocumented 存储过程sp_ms_marksystemobject

您的存储过程名称必须以sp_开头,例如sp_GetInvoices。在master数据库中创建它,然后调用exec sp_ms_marksystemobject sp_GetInvoices以使其查看当前数据库的表。

USE master
GO

CREATE OR ALTER PROCEDURE sp_GetInvoices  
AS
BEGIN
    SELECT ClientName from Invoice
END
GO

exec sp_ms_marksystemobject sp_GetInvoices

USE client1
GO

create table Invoice (ClientName varchar(100))
insert Invoice select 'Acme Client'

exec sp_GetInvoices 

结果(在SQL Server 13.0.5081.1版上运行):

ClientName
------------ 
Acme Client

答案 1 :(得分:0)

在“主”数据库上试试这个:

CREATE PROCEDURE [dbo].[GetDataFromClient]
    @DB VARCHAR(50)
AS
BEGIN

SET NOCOUNT ON;

DECLARE @STMT VARCHAR( 300 );
DECLARE @SP VARCHAR( 500 );


SET @SP = 'dbo.GetData';


SET @STMT = 'EXEC(''' +  @SP + ''')';   


EXEC('USE '+ @db + ';' + @STMT)

END

现在在“客户”数据库中:

CREATE TABLE [dbo].[TestClient](
    [ID] [int] NOT NULL,
    [Description] [varchar](10) NULL,
    CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)   WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY].

创建存储过程以从表TestClient

中检索数据
CREATE PROCEDURE [dbo].[GetData]
AS
BEGIN

    SELECT *
    FROM TestClient;

END

现在,您可以使用以下方法从TestClient数据库中检索列:

USE [TestMaster]
GO

DECLARE @return_value int

EXEC @return_value = [dbo].[GetDataFromClient]
     @DB = N'TESTCLIENT'

SELECT 'Return Value' = @return_value

GO  

答案 2 :(得分:-1)

创建链接服务器后,可以使用四个部件名称调用存储过程。 或者可以通过openquery选项调用它。

LinkSerevr:

EXEC [ServerName] .dbname.scheme.StoredProcedureName

openquery:SELECT * FROM OPENQUERY([ServerName] .dbname.scheme.StoredProcedureName)