1

I'm trying to print 'no data' for the null values in the tavg int datatype column but I keep getting a conversion failed error in the presence of the "then sum((tmin+tmax)/2)" portion. Any help?

    select
    Case 
    when (tavg > -59  and tmin is NULL and tmax is NULL ) then tavg
    when (tavg > -59 and tmin is NULL and tmax > -59) then tavg
    when (tavg is null and tmin >-59 and tmax > -59) then sum((tmin+tmax)/2)
    when (tavg is null and tmin is null and tmax is null) then 'No data'
    else cast(tavg as varchar(50)) end as 'avg_temp',
    case 
    when tmin is null then 'No data' else cast(tmin as varchar(50)) end as 'Minimum Temperature', 

1 Answer 1

4

In a case when all return types should be the same otherwise SQL will try to cast all return types to the highest precedence. The error you are getting is becuase SQL is trying to convert 'No Data' to int (higher precedence). If you return varchar from all cases it should work:

select
    Case 
    when (tavg > -59  and tmin is NULL and tmax is NULL ) then cast(tavg as varchar(50))
    when (tavg > -59 and tmin is NULL and tmax > -59) then cast(tavg as varchar(50))
    when (tavg is null and tmin >-59 and tmax > -59) then cast(sum((tmin+tmax)/2) as varchar(50))
    when (tavg is null and tmin is null and tmax is null) then 'No data'
    else cast(tavg as varchar(50)) end as 'avg_temp',
    case 
    when tmin is null then 'No data' else cast(tmin as varchar(50)) end as 'Minimum Temperature', 

Data Type Precedence (Transact-SQL)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.