How to replace a column values when querying with

2019-08-30 01:30发布

Alright let me explain my question with example

We have a table that contains

Id
Name
Number

Now example

1 House 4
2 Hospital 3
3 Airport 'null'
4 Station 2

 select t1.id, 
       t1.name,
       t2.name as name2
from your_table t1
left join your_table t2 on t1.number = t2.id

Ok when querying as the above, that 'null' value containing column is giving error. So i want to modify above query in a way that it will return name2 as null and won't give error for that rows.

So the result I expect should be:

1 House Station
2 Hospital Airport
3 Airport null
4 Station Hospital

This null here is as string.

The current error I get

Msg 245, Level 16, State 1, Line 5
Conversion failed when converting the varchar value 'null' to data type smallint.

thank you

1条回答
时光不老,我们不散
2楼-- · 2019-08-30 01:56

You should fix your database design. Meantime, use NULLIF to get your expected results:

select t1.id, 
       t1.name,
       t2.name as name2
from your_table t1
left join your_table t2 on NULLIF( t1.number, 'NULL' ) = t2.id
查看更多
登录 后发表回答