2013-06-03 70 views
-1

我有一个名为runTotal的字段名,它是一个整数。如何解决CASE语句错误?

我试图将值赋给最高的总CASE语句:

select (case when isnull(t.runtotal,90) = 0 then 'You have reached max total' else t.runtotal end) runtotal

我收到以下错误:

Conversion failed when converting the varchar value 'Class is full' to data type int 

如果我删除否则t.runtotal,它的工作原理,但我们希望的是别人的代码,因为默认值应该是90

任何想法如何解决这个问题?

非常感谢提前

+1

您可以通过铸造'runtotal'为varchar值'投解决这个问题(t.runtotal为varchar(10))'那么数据类型将是相同的。 – Taryn

回答

0

我终于解决了这个内容问题。下面是最终的解决方案:

(case when isnull(t.runtotal,9) = 0 then 'You have reached max total' 
else str(isnull(t.runtotal,9)) end) runtotal 
3

这是因为你正在返回不同的数据类型。
第一部分返回一个varchar,而else部分返回一个数字。

select 
-- this condition returns a varchar 
(case when isnull(t.runtotal,90) = 0 then 'You have reached max total' 
-- else condition is returning a number 
else t.runtotal 
end) runtotal. 

返回值的数据类型应该是相同的。
请纠正它。

0

此代码是说

select (case when isnull(t.runtotal,90) = 0 
    then 'You have reached max total' 
    else t.runtotal end) runtotal 

如果runTotal = 0,回到我一个字符串消息文本“您已达到最大总”。 否则,返回我一个整数告诉我跑总

这是说,还给我提供一个错误信息字符串,或运行总计转换为字符串

select (case when isnull(t.runtotal,90) = 0 
    then 'You have reached max total' 
    else Str(t.runtotal) end) runtotal 
+0

所有回复的人,我非常感谢你。 @shahkalpesh,我没有看到你的解决方案和我的任何区别。事实上,当我跑你的时候,我发现与我发布的错误一样。 Sparky,没有与您的错误,但再次,而不是runtotal为null时,默认值为90,所有行都是空白的。 任何其他的想法如何解决这个问题? –

+0

当runTotal为NULL时,你想显示什么?如果你想显示它,你可以简单地做IsNull(t.runtotal,90)作为RunTotal,但是你要在你的代码中进行比较......添加一些样本预期输出,我想人们将能够为你阐明SQL ... – Sparky

+0

是的,当runTotal为null且isNull(t.runtotal,90)为runTotal时,我可以显示90,但我们希望能够在值为0时显示'您已经达到最大总数'。这就是关键。我不确定谁扣2分。当你的问题不清楚时,我认为他们这样做。这个问题不可能更清楚。 当我们第一次运行应用时,我们想要将值加载为90,并且我们将继续向下计数直到0.我在这个论坛上看到类似的东西,但它对我不起作用。 –