四有青年加盟费用:将 varchar 值 '1,2,3,4' 转换为数据类型为 int 的列时发生语法错误。不明中

来源:百度文库 编辑:中科新闻网 时间:2024/04/19 21:35:36
存储过程如下:
CREATE PROCEDURE GetCommendarticle(
@id varchar(255),
@aid varchar(255)
)
AS
BEGIN
select * from article where id (@id) and author in (@aid)
END
GO
分析器中执行下列语句:
exec GetCommendarticle '2008,2009,2500','8,15'
出现下列错误:
服务器: 消息 245,级别 16,状态 1,过程 GetCommendarticle,行6将 varchar 值 '2008,2009,2500' 转换为数据类型为 int 的列时发生语法错误。

我想in是使用表达式列表,而此过程引用的是一个表达式,不知道有何最佳方法可以实现此功能,谢谢!
查了相关资料,我看到用到此函数CHARINDEX的方法来解决比较多,之前未使用过:-(
呵呵,不是路过!遇到困难的,就想到BAIDU。

article表中id和author都是int型的字段吧?
简单点的方法是,你在执行存储过程的时候两个参数写成有效的int型数据
比如
exec GetCommendarticle '2008','8'
不过看你的意思是想同时将多个值传入存储过程执行,按你现在的写法肯定不行。改进方法是在存储过程里对传进来的参数进行转换。
可以帮你写一个,不过怕你只是路过这里,写出来你也不看,所以暂时不写了。

既然不是路过就写出来你看看吧,其实就是利用charindex找到逗号,然后分割各个id。另外,最好在存储过程里加上判断@tempstr是不是有效的数字的代码,你可以自己来完善。

CREATE PROCEDURE GetCommendarticle(
@id varchar(255),
@aid varchar(255)
)
AS

declare @pos int
declare @oldPos int
declare @tempstr varchar(100)

create table #temp_id
(
id int
)
create table #temp_aid
(
id int
)

set @pos=1
set @oldPos=1
while @pos<len(@id)
begin
set @pos=charindex(',',@id,@oldpos)
if @pos>0
begin
set @tempstr=substring(@id,@oldpos,@pos-@oldpos)
set @oldpos=@pos+1
end
else
begin
set @tempstr=substring(@id,@oldpos,len(@id)-@oldpos+1)
set @pos=len(@id)
end
insert into #temp_id
select @tempstr
end

set @pos=1
set @oldPos=1
while @pos<len(@aid)
begin
set @pos=charindex(',',@aid,@oldpos)
if @pos>0
begin
set @tempstr=substring(@aid,@oldpos,@pos-@oldpos)
set @oldpos=@pos+1
end
else
begin

set @tempstr=substring(@aid,@oldpos,len(@aid)-@oldpos+1)
set @pos=len(@aid)
end
insert into #temp_aid
select @tempstr
end

select * from article where id in (select id from #temp_id where id is not null) and author in (select id from #temp_aid where id is not null)

drop table #Temp_id
drop table #temp_aid