How to list all tables & columns names of a linked-server database in SQL Server?

前端 未结 4 1929
情书的邮戳
情书的邮戳 2021-01-13 02:20

If it\'s a regular database, i can simply use this query to get a list of all table names and their column names of the database.

use [my_database_name]
GO

         


        
相关标签:
4条回答
  • 2021-01-13 02:47

    The system stored procedure sp_tables is used to list out the tables available in the current database of the current server. You can use sp_tables_ex for the linked server. The following returns list of tables available in the specified Server:

    EXEC sp_tables_ex @table_server = 'MYSQL_DB'
    
    0 讨论(0)
  • 2021-01-13 02:53

    Fully qualify your linked server in your FROM and JOIN, and alias them.

    SELECT lst.name AS Table_Name, 
           lsc.name AS Column_Name, 
           lsc.max_length, 
           (schema_id) As Schema_name
    
    FROM [SERVER].[DB].[sys].[tables] lst
        INNER JOIN [SERVER].[DB].[sys].[columns] lsc
            ON lst.OBJECT_ID=lsc.object_id
    
    ORDER BY schema_name, lst.name, lsc.name
    
    0 讨论(0)
  • 2021-01-13 03:03

    To expand slightly on @scsimon's answer...

    The (schema_id) As Schema_name is not very useful, as it's really an ID. To get the list of all tables (and their columns) with actual schema names one can use:

    SELECT s.name AS schema_name
          ,t.name AS table_Name
          ,c.name AS column_Name
        --,c.max_length
    FROM [SERVER].[DB].sys.tables t
    JOIN [SERVER].[DB].sys.schemas s ON t.schema_id = s.schema_id
    JOIN [SERVER].[DB].sys.columns c ON t.object_id = c.object_id
    --WHERE s.name = 'dbo'
    ORDER BY s.name, t.name, c.name
    
    0 讨论(0)
  • 2021-01-13 03:11

    There is the solution to list:

    declare @temp table
    (
        col1 varchar(255),
        col2 varchar(255),
        [name] varchar(255),
        [type] varchar(255),
        col3 varchar(255)
    )
    insert @temp exec sp_tables_ex 'Your_LinkedServer_Name'
    select * from @temp
    

    And also open a cursor:

    DECLARE lstTables CURSOR FOR 
            select [name] from @temp
    
    0 讨论(0)
提交回复
热议问题