1

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 database name. To do this I tried to use this code:

Declare @dbName varchar(50)='Learn'

use @dbname
go

select TABLE_NAME  
from INFORMATION_SCHEMA.TABLES

But it does not work. How can I do this ?

3 Answers 3

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

OR SIMPLY:

SELECT TABLE_NAME FROM Learn.INFORMATION_SCHEMA.TABLES
Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.