Matt Schubert
Matt Schubert

Reputation: 1003

SQL Insert column names as data

Is there a SQL Query to insert the column names from Table A into the rows in Table B?

Upvotes: 1

Views: 5258

Answers (4)

jarandaf
jarandaf

Reputation: 4427

    INSERT INTO B    
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.Columns
    WHERE TABLE_NAME = 'A'

should work...

Upvotes: 2

Jimmy Sawczuk
Jimmy Sawczuk

Reputation: 13614

Might be different depending on your actual software, but for MySQL this should work:

 INSERT INTO table_b (col_name)
     SELECT Field FROM (DESCRIBE table_a)

Upvotes: 1

Martin Smith
Martin Smith

Reputation: 454000

(Using INFORMATION_SCHEMA for an attempt at maximum portability)

INSERT INTO B
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='A' AND TABLE_SCHEMA='FOO'

Upvotes: 2

SWeko
SWeko

Reputation: 30942

As column names are essencially strings, yes, you can insert them into other tables.

The harder (and implied) part of the question, is "How do I get a list of columns for a given table", and the answer to that question depends on the database you are using.

Also, in my experience, storing database metadata into your database, can be indicative of design problems.

Upvotes: 6

Related Questions