日期:2014-05-18  浏览次数:20453 次

"In"函数在存储过程中报错
ALTER proc [dbo].[NSP_SelectResultListByTime]
@PIDList varchar(50),
@MyDateTime nvarchar(50)
as
if(LEN(@MyDateTime)=8)
begin
  select PID,Sum(Value) as SumValue,RIGHT(MyDateTime,2) as DaTime from ResultList where PID in (@PIDList) and Left(MyDateTime,8)=@MyDateTime group by PID,RIGHT(MyDateTime,2),Left(MyDateTime,8)
end

问题:传入“String”参数("16,15,14"),执行存储过程时发生了错误,信息如下:
在将 varchar 值 '16,15,14' 转换成数据类型 int 时失败。

“@PIDList varchar(50)”变量声明的不对么???应该怎样修改呢???为什么呢???
 

------解决方案--------------------
要么动态拼接 exec 

要么用charindex
------解决方案--------------------
SQL code
--exec示例
if object_id('[tablename]') is not null drop table [tablename]
create table [tablename] (id int,name varchar(1))
insert into [tablename]
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e' union all
select 6,'f'

DECLARE @i VARCHAR(30) SET @i='1,4'
EXEC('select * from [tablename] WHERE id IN ('+@i+')')
/*
id          name
----------- ----
1           a
4           d
*/

--charindex示例
if object_id('[tablename]') is not null drop table [tablename]
create table [tablename] (id int,name varchar(1))
insert into [tablename]
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e' union all
select 6,'f'

DECLARE @i VARCHAR(30) SET @i='1,4'

SELECT * FROM [tablename] 
WHERE CHARINDEX(','+LTRIM(id)+',',','+@i+',')>0

/*
id          name
----------- ----
1           a
4           d
*/

------解决方案--------------------
DECLARE @sql varchar(5000)
set @sql='select PID,Sum(Value) as SumValue,RIGHT(MyDateTime,2) as DaTime from ResultList where PID in (' + @PIDList +') and Left(MyDateTime,8)=@MyDateTime group by PID,RIGHT(MyDateTime,2),Left(MyDateTime,8)'
exec (@sql)

------解决方案--------------------
问题:传入“String”参数("16,15,14"),执行存储过程时发生了错误,信息如下:
在将 varchar 值 '16,15,14' 转换成数据类型 int 时失败。

楼主试试传入参数“'16','15','14'”, 传入参数时把单引号也补上。
下面语句我测了可以工作。
SQL code
SELECT * FROM tablename WHERE 12 IN('12','13')

------解决方案--------------------
LZ这样传参数相当于直接传了一个字符串到IN里面,也就是只是一个值,而不是你想象的是数字的序列所以才会报错。SQL是将整个@PIDList当成一个串整体处理的。