Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
C#
how to insert only one table's all column name into another table's only one column in sql


What I have tried:

I DO NOT KNOW

sql - Inserting Column Name into a Table - Stack Overflow[^]
Posted
Updated 1-Nov-16 18:41pm
Comments
Tomas Takac 1-Nov-16 8:38am    
Did you try what was recommended in the SO question? What is your query? What is the result? Do you get an error?

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='YourTableName'

Try:
SQL
INSERT INTO dbo.DestinationTable (ColumnName)
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = 'SourceTable'
 
Share this answer
 
If I understand the question correctly, you want the list into a single column in a single row. If that is the case, consider the following:
SQL
WITH ColumnnList (List) AS (
   SELECT ';' + c.Column_Name
   FROM INFORMATION_SCHEMA.Columns c
   WHERE c.Table_Name = 'SOURCETABLENAME'
   FOR XML PATH ('')
) 
INSERT INTO TARGETTABLENAME (TARGETCOLUMNNAME)
SELECT SUBSTRING(a.List, 2, 99999)
FROM ColumnnList a

Just remember to change:

  • SOURCETABLENAME to the name of the table for which to list the columns
  • TARGETTABLENAME to the name of the table where you want to insert the data
  • TARGETCOLUMNNAME to the name of the target column in the target table
  • optionally change the separator to what you wish. I've used semicolon (;)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900