How to replace a column values when querying with left join command SQL Server 2008 r2

南笙酒味 提交于 2019-12-12 03:30:45

问题


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:


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


来源:https://stackoverflow.com/questions/12771906/how-to-replace-a-column-values-when-querying-with-left-join-command-sql-server-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!