SQL存储过程错误将数据类型varchar转换为bigint

时间:2016-10-11 08:33:03

标签: sql sql-server

我正在使用SQL Server 2012,我有一个存储过程。我收到上述错误的最后一部分是这部分:

Set @SQL = '
Select Style=case when AttNr = 2 then '''' else Entity end'+@SQL+' 
 From  #Temp 
 Where Entity not in (Select Entity From #Temp Where AttNr=2 Group By Entity Having Sum(cast(Value as bigint))=0) 
 Group By Entity,AttNr 
 Order By Entity,AttNr
'

我哪里错了?

更新至:

Set @SQL = '
Select Style=case when AttNr = 2 then '''' else Entity end'+@SQL+' 
 From  #Temp 
 Where Entity not in (Select cast(Entity as varchar(100)) From #Temp Where AttNr=2 Group By Entity Having Sum(cast(Value as bigint))=0) 
 Group By Entity,AttNr 
 Order By Entity,AttNr
'

我必须做些蠢事 - 改为:

Set @SQL = '
Select Style=case when AttNr = ''2'' then '''' else Entity end'+@SQL+' 
 From  #Temp 
 Where Entity not in (Select cast(Entity as varchar(100)) From #Temp Where AttNr=2 Group By Entity Having Sum(cast(Value as bigint))=0) 
 Group By Entity,AttNr 
 Order By Entity,AttNr
'

好的,我改到了下面:

Set @SQL = '
Select Style=case when AttNr = ''2'' then '''' else cast(Entity as varchar(100)) end'+@SQL+' 
 From  #Temp 
 Where Entity not in (Select cast(Entity as varchar(100)) From #Temp Where AttNr=''2'' Group By Entity Having Sum(cast(Value as bigint))=0) 
 Group By Entity,AttNr 
 Order By Entity,AttNr
'

但仍然没有 - 同样的错误。

谢谢,

迈克尔

2 个答案:

答案 0 :(得分:1)

DO

cast(Entity as varchar(100))

您收到错误是因为Case遵循数据类型优先级。然后,Then和Else中的值将转换为具有更高优先级的相同数据类型

以下示例:

Declare @a int=1
select case when @A=1 then '''' else cast(@a as varchar(10)) end

错误:
将varchar值'''转换为数据类型int时,转换失败。

也有可能,AttNr有一些varchar值,所以如果是这样的话,请尝试隐式转换为varchar。

AttNr ='2

答案 1 :(得分:-1)

也许您的数据为空,无法转换为bigint .... 只需在查询中替换这段代码......

SUM((CAST(ISNULL(Value , '0') as bigint)))

为任何应该施放的空值执行...