How to use database name dynamically in SQL Server

前端 未结 3 1945
伪装坚强ぢ
伪装坚强ぢ 2021-01-28 07:29

I need to get all table names in SQL Server. To do this I use this code:

select TABLE_NAME  
from INFORMATION_SCHEMA.TABLES

I need use dynamic

相关标签:
3条回答
  • 2021-01-28 08:17

    Create this stored procedure in master db and call it

    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
    

    OR you can try this

    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;
    
    0 讨论(0)
  • 2021-01-28 08:18
    DECLARE @sql varchar(max)
    Declare @dbName varchar(50)='Learn'
    SET @sql='
    use '+@dbname+'
    go
    
    select TABLE_NAME  
    from INFORMATION_SCHEMA.TABLES'
    exec (@sql)
    
    0 讨论(0)
  • 2021-01-28 08:32
    DECLARE @dbName varchar(50)='Learn'
    EXEC ('SELECT TABLE_NAME FROM ' +@dbName+'.INFORMATION_SCHEMA.TABLES');
    

    OR SIMPLY:

    SELECT TABLE_NAME FROM Learn.INFORMATION_SCHEMA.TABLES
    
    0 讨论(0)
提交回复
热议问题