简体   繁体   中英

Gather all column names into a table

I am working on a project whos purpose is to rename all table names and column names in the sql database from one language to another. I have gather all the local table names into a table ltbl_TableNames and want to add all the columns of these tables into a table called ltbl_TableColumns.

I also want every table column to have a link to their table name. For example, the table 'Sales' have a column named 'Sum'. The table 'Sales' has the ID '10000'. I want to add that ID in a column named 'TableName_ID' for linking purposes. Is this possible to do without a lot of hassle?

Disclaimer: I am thinking about the renaming process. I only want to gather the column names with link to their parent table name.

Thanks in advance for answers.

You may use sys.tables for getting list of table name in your database. Similarly for column name you may use information_schema.columns as this will give records with table name . From the above 2 records you can easily make you required result.

            ;WITH CTABLE AS 
        ( SELECT * FROM SYS.TABLES WHERE TYPE_DESC = 'USER_TABLE' )
        , COLUMNNAME AS 
        ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS )
        SELECT * INTO NEWTABLE FROM 
        (SELECT CTABLE.NAME AS TABLENAME , COLUMNNAME.COLUMN_NAME, COLUMNNAME.COLUMN_NAME + '_' + CAST(CTABLE.OBJECT_ID AS VARCHAR(15)) AS NEW_COLUMNNAME   
        FROM CTABLE INNER JOIN COLUMNNAME ON CTABLE.NAME = COLUMNNAME.TABLE_NAME ) AS D 

You may try this for your result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM