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

前端 未结 4 2005
情歌与酒
情歌与酒 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:32

    The only alternative is to avoid SELECTing *:

    TableA

    foo | bar
    ---------
    

    TableB

    foo | baz
    ---------
    

    When selecting * from both tables, you'll end up with 2 columns named foo, which is not allowed in a single table.

    Name the selected columns using unique names, and this will work.

    SELECT INTO #TableTemp t1.foo foo1, t1.bar, t2.foo foo2, t2.baz
    FROM tableA t1
    INNER JOIN tableB t2 ON t1.foo = t2.foo
    

    But while you're at it, no need to insert the common column twice (as t1.foo = t2.foo). Select just one of them:

    SELECT INTO #TableTemp t1.foo, t1.bar, t2.baz
    FROM tableA t1
    INNER JOIN tableB t2 ON t1.foo = t2.foo
    

    EDIT: As stated by Philip Kelley, this problem only occurs when you try to save the resultset into a table. As long as you only select data, everything works fine with duplicate column names.

提交回复
热议问题