How to use database name dynamically in SQL Server

前端 未结 3 1948
伪装坚强ぢ
伪装坚强ぢ 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;
    

提交回复
热议问题