Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all columns of a table from a different database

s there a syntax wherein I can get the columns of a table from a different database? I have tried using select column_name from information_schema.columns where table_name = 'Database_Name.DBO.Table_Name' But it's not working. Please do help me, been doing this for days.

like image 671
eljon_i3 Avatar asked Jan 12 '15 03:01

eljon_i3


People also ask

How do I retrieve all columns in a table?

To retrieve all columns, use the wild card * (an asterisk). The FROM clause specifies one or more tables to be queried. Use a comma and space between table names when specifying multiple tables. The WHERE clause selects only the rows in which the specified column contains the specified value.

How do I extract data from multiple databases?

Create a Java data access class that contains the columns you want to retrieve. Retrieve the rows from each of the databases separately, creating a List of data access objects. Combine this Lists in Java to create one master List of data access objects.

How can I get all columns of all tables in SQL?

You can use following query to list all columns or search columns across tables in a database. USE AdventureWorks GO SELECT t.name AS table_name, SCHEMA_NAME(schema_id) AS schema_name, c.name AS column_name FROM sys. tables AS t INNER JOIN sys. columns c ON t.


2 Answers

You're close. TABLE_NAME has just the name of the table. The rest of the information is in TABLE_CATALOG and TABLE_SCHEMA. You can qualify information_schema with the catalog you want to select from:

select column_name from Database_Name.information_schema.columns
where table_name = 'Table_Name' AND table_schema = 'dbo'
like image 131
Eric J. Avatar answered Sep 28 '22 19:09

Eric J.


This is what I found out. Each database has its own information_schema view so it won't show the information from the other databases. So if you want to get the column names for a table in another database, you have to use the information_schema view of that database.

{database name}.information_schema

Example:

SET @Sql = CONCAT('INSERT INTO ', @DBName, '.dbo.colname_table (column_name) 
    SELECT COLUMN_NAME FROM ', @DBName, '.INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = ''table_name'' AND TABLE_SCHEMA = ''dbo'' 
    ORDER BY ORDINAL_POSITION');

EXECUTE sp_executesql @Sql;

where @DBName is the name of the database.

like image 35
Carlo Avatar answered Sep 28 '22 17:09

Carlo