T-SQL可以在select语句中使用变量来指定数据库

时间:2021-09-11 01:41:24

Is there a way to do something like this without converting the sql to a string and calling exec

有没有办法做这样的事情而不将sql转换为字符串并调用exec

DECLARE @source_database varvhar(200)
SELECT @source_database = 'wibble'

SELECT * FROM SELECT @source_database.dbo.mytable

3 个解决方案

#1


3  

No. I'm afraid not.

不,我不敢。

It is necessary to use dynamic sql in order to use a variable for either a database or column name.

必须使用动态sql才能将变量用于数据库或列名。

#2


2  

Only for stored procs without using linked server or dynamic SQL

仅适用于未使用链接服务器或动态SQL的存储过程

DECLARE @myProc  varchar(200)
SELECT @myProc  = 'wibble.dbo.foobar'

EXEC @myProc

#3


0  

There is another (not necessarily pretty) alternative:

还有另一种(不一定是漂亮的)替代方案:

IF (@source_database = 'wibble')
    USE wibble;
ELSE IF (@source_database = 'wibble2')
    USE wibble2;
ELSE
    RAISERROR(....)

SELECT * FROM dbo.myTable

If you have any real number of databases, this may be tiresome. But it's an option nonetheless.

如果您有任何实际数量的数据库,这可能会很烦人。但它仍然是一个选择。

#1


3  

No. I'm afraid not.

不,我不敢。

It is necessary to use dynamic sql in order to use a variable for either a database or column name.

必须使用动态sql才能将变量用于数据库或列名。

#2


2  

Only for stored procs without using linked server or dynamic SQL

仅适用于未使用链接服务器或动态SQL的存储过程

DECLARE @myProc  varchar(200)
SELECT @myProc  = 'wibble.dbo.foobar'

EXEC @myProc

#3


0  

There is another (not necessarily pretty) alternative:

还有另一种(不一定是漂亮的)替代方案:

IF (@source_database = 'wibble')
    USE wibble;
ELSE IF (@source_database = 'wibble2')
    USE wibble2;
ELSE
    RAISERROR(....)

SELECT * FROM dbo.myTable

If you have any real number of databases, this may be tiresome. But it's an option nonetheless.

如果您有任何实际数量的数据库,这可能会很烦人。但它仍然是一个选择。