views:

119

answers:

4

I want to get the results of a left join between two tables, with both having a column of the same name, the column on which I join. The following query is seen as valid by the import/export wizard in SQL Server, but it always gives an error. I have some more conditions, so the size wouldn't be too much. We're using SQL Server 2000 iirc and since we're using an externally developed program to interact with the database (except for some information we can't retrieve that way), we can not simply change the column name.

SELECT table1.*, table2.* 
FROM table1 
LEFT JOIN table2 ON table1.samename = table2.samename

At least, I think the column name is the problem, or am I doing something else wrong?

A: 

Do more columns than just your join key have the same name? If only your join key has the same name then simply select one of them since the values will be equivalent except for the non-matching rows (which will be NULL). You will have to enumerate all your other columns from one of the tables though.

SELECT table2.samename,table1.othercolumns,table2.*
FROM table1 
LEFT JOIN table2 ON table1.samename = table2.samename
bot403
I think this column is the only one appearing in both. I expected that using table1.* and table2.* after select would result in the column names in the results table being table1.* and table2.* so there wouldn't be the column name problem (one being returned as table1.samename and the other as table2.samename). I wanted to avoid enumerating all the columns of one of the tables
Ernst
A: 

You may need to explicitly list the columns from one of the tables (the one with less fields), and leave out the 2nd instance of what would be the duplicate field..

select Table1.*, {skip the field Table2.sameName} Table2.fld2, Table2.Fld3, Table2.Fld4...  from

Since its a common column, it APPEARS its trying to create twice in the result set, thus choking your process.

DRapp
A: 

Since you should never use select *, simply replace it with the column names of the columns you want. THe join column has the same value (or null) in both sides of the join, so only select one of themm the one from table1 which will always have the value.

HLGEM
A: 

If you want to select all the columns from both tables just use Select * instead of including the tables separately. That will however leave you with duplicate column names in the result set, so even reading them out by name will not work and reading them by index will give inconsistent results, as changing the columns in the database will change the resultset, breaking any code depending on the ordinals of the columns.

Unfortunately the best solution is to specify exactly the columns you need and create aliases for the duplicates so they are unique.

I quickly get the column headings by setting the query to text mode and copying the top row ...

Cobusve