'Conversion failed when converting the nvarchar value 'NULL' to data type int with Replace function only
I have three tables in my database with the following properties:
create table #Step_1
(
ID int identity,
Recipient_ID varchar(50),
Diag_ID varchar(50),
Diag_Group varchar(50),
Class Int,
[Rank] Int
)
create table #tmp_indx
(
Recipient_ID varchar(50),
DIAG_ID varchar(50),
DIAG_ID_UPDATED varchar(50)
)
update #tmp_indx
Set DIAG_ID_Updated = REPLACE(DIAG_ID, '.','')
create table #cdps_format
(
DIAG_ID varchar(50),
DIAG_Group varchar(50),
Class varchar(50),
Rank varchar(50)
)
So now when I run this query, everything runs smoothly
insert into #Step_1 ( Recipient_ID,
Diag_ID,
Diag_Group,
Class,
[Rank]
)
select Recipient_ID,
Diag_ID,
Diag_Group,
Class,
[Rank]
from
(select a.Recipient_ID,
a.DIAG_ID,
b.Diag_Group,
b.Class,
b.[Rank],
ROW_NUMBER() OVER (PARTITION BY Recipient_ID, Class ORDER BY [Rank]) AS rn
from #tmp_indx a
inner join #cdps_format b
on a.DIAG_ID = b.diag_id) d
where d.rn = 1
order by recipient_id, diag_id
But as soon as I change a.DIAG_ID to a.DIAG_ID_UPDATED in the inner join, I get the error:
Conversion failed when converting the nvarchar value 'NULL' to data type int
Does anyone have any idea why this happens? From what I understand, DIAG_ID_UPDATED is just DIAG_ID but removed any '.' from the variable, so I am a bit confused why this is happening. I thought it would be that both rank and class are characters in #cdps_format and that they are INT in #step_1, but that doesn't really explain to me why the error only occurs after changing the variable in the join. Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|