设置CASE语句,以便所有结果都是Varchar

时间:2017-09-14 10:02:02

标签: sql-server case

我正在使用下面的查询,但收到错误

'Conversion failed when converting the varchar value '8-14' to data type int.'

我认为它是因为第二行返回一个整数而其余的不是,这是正确的吗?

我不打算计算这个字段,所以如果它们都需要是相同类型的值,让第二行返回varchar就好了。我尝试过使用'convert'但我不知道我认为我的语法正确。

,(case when AppointmentCancellationDate = null Then 'NoDate'
when (datediff(day,BasicStartDate,AppointmentCancellationDate)) < '8' then (datediff(day,BasicStartDate,AppointmentCancellationDate))
when (datediff(day,BasicStartDate,AppointmentCancellationDate)) <15 then '8-14'
when (datediff(day,BasicStartDate,AppointmentCancellationDate)) <22 then '15-21'
Else '+22'  end) as CancWindowGroup

2 个答案:

答案 0 :(得分:3)

尝试以下方法:

,(case when AppointmentCancellationDate is null Then 'NoDate'
when (datediff(day,BasicStartDate,AppointmentCancellationDate)) <8 then cast(datediff(day,BasicStartDate,AppointmentCancellationDate) as nvarchar(10))
when (datediff(day,BasicStartDate,AppointmentCancellationDate)) <15 then '8-14'
when (datediff(day,BasicStartDate,AppointmentCancellationDate)) <22 then '15-21'
Else '+22'  end) as CancWindowGroup

答案 1 :(得分:1)

与NoDate&#39;您将案例的结果定义为varchar。第二行产生int - 所以存在类型冲突。