转换varchar值时,转换失败'字符串'到数据类型int

时间:2017-03-14 05:18:49

标签: sql-server

我试图打印“没有数据”。对于tavg int数据类型列中的空值,但是在存在"然后总和((tmin + 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', 

1 个答案:

答案 0 :(得分:4)

在所有返回类型应该相同的情况下,否则SQL将尝试将所有返回类型强制转换为最高优先级。您得到的错误是因为SQL试图将“无数据”转换为int(更高的优先级)。如果从所有情况返回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', 

Data Type Precedence (Transact-SQL)