3

Specifically, can I call a proc from the current database in a view. I already know about the openrowset hack, so this works, for example:

create view MyView as
    select *
    from openrowset (
        'sqloledb',
        'server=(local);trusted_connection=yes;',
        'exec MyDatabase.dbo.MyStoredProcedure' -- Works fine
    )

But I'd like to be able to call the proc from the current DB without hard-coding the name like so:

create view MyView as
    select *
    from openrowset (
        'sqloledb',
        'server=(local);trusted_connection=yes;',
        'exec ' + db_name() + '.dbo.MyStoredProcedure' -- Don't want to hard-code DB name
    )

This doesn't work, unfortunately, as openrowset expects literal strings, rather than variables of any sort.

Regardless of security and performance considerations, is there a workaround? It would make the maintenance of a legacy system much more bearable, as the proc that this view will call connects to a different database depending upon environment (dev, test, prod).

4

1 に答える 1

2

いいえ、ビューで動的 SQL を使用することはできません。異なる「環境」が 3 つしかない場合は、3 つのビューを作成したり、環境に応じて同義語を使用したりできます。たとえば、次の 3 つのビュー (疑似/トリミング) を使用できます。

create view dbo.devMyView as
    select * ... 'exec Dev.dbo.MyStoredProcedure'
go
create view dbo.testMyView as
    select * ... 'exec Test.dbo.MyStoredProcedure'
go
create view dbo.prodMyView as
    select * ... 'exec Prod.dbo.MyStoredProcedure'

次に、コードで動的 SQL を使用して、必要なビューを指定するか、各環境をシミュレートするときにシノニムをドロップして作成することができます。

DROP SYNONYM dbo.MyView;
GO
CREATE SYNONYM dbo.MyView FOR dbo.devMyView;

これで、dbo.MyView を参照するコードは、最終的に dev データベースのストアド プロシージャを呼び出します。これの欠点は、常に 1 つのシノニムしかアクティブ/リダイレクトできないことです。

于 2012-05-16T21:27:02.877 に答える