View error in PostgreSQL

前端 未结 4 1347
南旧
南旧 2021-01-01 18:41

I have a large query in a PostgreSQL database. The Query is something like this:

SELECT * FROM table1, table2, ... WHERE table1.id = table2.id...
         


        
4条回答
  •  灰色年华
    2021-01-01 19:14

    No built-in way in the language to solve it (and frankly, * is a bad practice in general because it can cause latent defects to arise as the table schemas change - you can do table1.*, table2.acolumn, tabl2.bcolumn if you want all of one table and selectively from another), but if PostgreSQL supports INFORMATION_SCHEMA, you can do something like:

    DECLARE @sql AS varchar
    
    SELECT @sql = COALESCE(@sql + ', ', '') 
        + '[' + TABLE_NAME + '].[' + COLUMN_NAME + ']'
        + CHAR(13) + CHAR(10)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME IN ('table1', 'table2')
    ORDER BY TABLE_NAME, ORDINAL_POSITION
    
    PRINT @sql
    

    And paste the results in to save a lot of typing. You will need to manually alias the columns which have the same name, of course. You can also code-gen unique names if you like (but I don't):

    SELECT @sql = COALESCE(@sql + ', ', '') 
        + '[' + TABLE_NAME + '].[' + COLUMN_NAME + '] '
        + 'AS [' + TABLE_NAME + '_' + COLUMN_NAME + ']'
        + CHAR(13) + CHAR(10)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME IN ('table1', 'table2')
    ORDER BY TABLE_NAME, ORDINAL_POSITION
    

提交回复
热议问题