I'm having trouble getting the right conversion without removing any values from the output.
I'd like to join two tables, but the primary key on one table is a char(4)
and the other one has it as an INT
.
Here is what I have done so far:
select A.ID,
B.ID from
TableA A
left join tableB B on
cast(a.ID as varchar(4) = B.ID
I realized that this does not bring single digit values.
Table A values: 0,1,2,3,41
Table B values: 0,1,2,3,41
My output with my original query only gives me 41 and forgets about the other 4 values.
I need to be able to get the other 4 values
Any ideas on how I can get my desired out put?
I just tested this out using temp tables and it all works as expected (I did add a closing )
)
create table #tableA(id int)
insert #tablea (id) values (0), (1), (2), (3), (41)
create table #tableb(id char(4))
insert #tableb (id) values (0), (1), (2), (3), (41)
select A.ID,
B.ID from
#TableA A
left join #tableB B on
cast(a.ID as varchar(4)) = B.ID
You can convert to strings:
select A.ID, B.ID
from TableA A left join
tableB B
on cast(a.ID as varchar(4)) = B.ID;
As I've learned from painful experience, this does not handle leading zeros or 0 decimals. So 0.00
is not the same as 000
. However, this should be fine for single digits unless there is zero padding.
For numeric comparisons, go in the other direction
select A.ID, B.ID
from TableA A left join
tableB B
on a.ID = try_convert(int, B.ID);
Of course, the real solution is to fix your tables so the columns have the same data type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.