SQL select join: is it possible to prefix all columns as 'prefix.*'?

后端 未结 22 1847
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 06:20

I\'m wondering if this is possible in SQL. Say you have two tables A and B, and you do a select on table A and join on table B:

SELECT a.*, b.* FROM TABLE_A a         


        
22条回答
  •  囚心锁ツ
    2020-12-02 06:34

    Developing from this solution, this is how I would approach the problem:

    First create a list of all the AS statements:

    DECLARE @asStatements varchar(8000)
    
    SELECT @asStatements = ISNULL(@asStatements + ', ','') + QUOTENAME(table_name) + '.' + QUOTENAME(column_name) + ' AS ' + '[' + table_name + '.' + column_name + ']'
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'TABLE_A' OR TABLE_NAME = 'TABLE_B'
    ORDER BY ORDINAL_POSITION
    

    Then use it in your query:

    EXEC('SELECT ' + @asStatements + ' FROM TABLE_A a JOIN TABLE_B b USING (some_id)');
    

    However, this might need modifications because something similar is only tested in SQL Server. But this code doesn't exactly work in SQL Server because USING is not supported.

    Please comment if you can test/correct this code for e.g. MySQL.

提交回复
热议问题