如何在SQL Server中动态使用数据库名称

时间:2015-03-31 09:05:02

标签: sql sql-server

我需要在SQL Server中获取所有表名。为此,我使用以下代码:

select TABLE_NAME  
from INFORMATION_SCHEMA.TABLES

我需要使用动态数据库名称。为此,我尝试使用此代码:

Declare @dbName varchar(50)='Learn'

use @dbname
go

select TABLE_NAME  
from INFORMATION_SCHEMA.TABLES

但它不起作用。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

DECLARE @dbName varchar(50)='Learn'
EXEC ('SELECT TABLE_NAME FROM ' +@dbName+'.INFORMATION_SCHEMA.TABLES');

或简单:

SELECT TABLE_NAME FROM Learn.INFORMATION_SCHEMA.TABLES

答案 1 :(得分:2)

在master db中创建此存储过程并将其命名为

CREATE PROCEDURE custom_query_executor
    @dbName     VARCHAR(50)
AS
BEGIN
    DECLARE @query_string nvarchar(4000);

    SET @query_string = 'select TABLE_NAME from ' + CAST(@dbName AS NVARCHAR) +'.INFORMATION_SCHEMA.TABLES';
    EXEC sys.sp_executesql @query_string;
END

或者你可以试试这个

DECLARE @dbName VARCHAR(50);
SET @dbName = 'Learn';

SET @query_string = 'select TABLE_NAME from ' + CAST(@dbName AS NVARCHAR) +'.INFORMATION_SCHEMA.TABLES';
EXEC sys.sp_executesql @query_string;

答案 2 :(得分:1)

DECLARE @sql varchar(max)
Declare @dbName varchar(50)='Learn'
SET @sql='
use '+@dbname+'
go

select TABLE_NAME  
from INFORMATION_SCHEMA.TABLES'
exec (@sql)