Alternatives to USING in a JOIN for SQL Server for avoiding duplicated columns in joined table

前端 未结 4 2008
情歌与酒
情歌与酒 2020-12-22 12:02

SQL Server does not offer the keyword USING in the context of a JOIN,
nor it provides a NATURAL JOIN.

Besides explicitly (manually) listing all the columns (link

4条回答
  •  死守一世寂寞
    2020-12-22 12:18

    I wouldn't recommend this, but in an effort to answer your question, you could create a sql clause builder function that automatically creates column aliases for your individual tables prefixed with the tablename (or customize it if you'd like):

    declare @tableName nvarchar(100);
    
    
    set @tableName = 'TestTable';
    
    select @tableName + '.' + c.name + ' AS ' + @tableName + '_' + c.name
    from sys.tables t
        inner join sys.columns c on c.object_id = t.object_id
    where
        t.name = @tableName
    

    Output for my little 2-column table

    TestTable.TestColumn1 AS TestTable_TestColumn1
    TestTable.TestColumn2 AS TestTable_TestColumn2
    

    Hypothetical usage

    declare @sql nvarchar(1000) = '';
    set @sql = myClauseBuilder('TestTable');
    
    set @sql = @sql + ',' + myClauseBuilder('TestTable2');
    
    set @sql = @sql + ' FROM TestTable INNER JOIN TestTable2....(etc.)
    
    exec @sql
    

提交回复
热议问题