Sql server 将varchar值“string”转换为数据类型int时获取转换失败

Sql server 将varchar值“string”转换为数据类型int时获取转换失败,sql-server,Sql Server,我正在尝试打印tavg int datatype列中null值的“无数据”,但在存在当时的sumtmin+tmax/2部分时,我一直收到一个转换失败的错误。有什么帮助吗 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

我正在尝试打印tavg int datatype列中null值的“无数据”,但在存在当时的sumtmin+tmax/2部分时,我一直收到一个转换失败的错误。有什么帮助吗

    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', 

在所有返回类型都应该相同的情况下,否则SQL将尝试将所有返回类型强制转换为最高优先级。您得到的错误是因为SQL试图将“无数据”转换为更高优先级的整数。如果在所有情况下都返回varchar,它应该可以工作:

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', 

在所有返回类型都应该相同的情况下,否则SQL将尝试将所有返回类型强制转换为最高优先级。您得到的错误是因为SQL试图将“无数据”转换为更高优先级的整数。如果在所有情况下都返回varchar,它应该可以工作:

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',