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

这么简单的存储过程到底错在哪里了?多谢
执行这条语句没问题:
select   id,sum(fileld1)   from   table1   where   id   in(2,8)   group   by   id
但是写成下面的存储过程后,总报错,执行不成功。
CREATE   PROCEDURE   test  
@id   nvarchar(500)
AS
begin
select   id,sum(fileld1)   from   table1   where   id   in(@id)   group   by   id
end
GO
执行exec   test   '2,8 '报如下错误:
服务器:   消息   8114,级别   16,状态   5,过程   test,行   5
将数据类型   nvarchar   转换为   bigint   时出错。
但是执行exec   test   '2 '或者exec   test   '8 '都没问题。

存储过程应该怎么写?错哪里了?奇怪!请大侠帮助,谢谢!

------解决方案--------------------

CREATE PROCEDURE test
@id nvarchar(500)
AS
begin
declare @sql varchar(8000)

set @sql = 'select id,sum(fileld1) from table1 where id in( ' + @id + ') group by id '

exec (@sql)

end
GO
------解决方案--------------------
加上一對括號
------解决方案--------------------
用动态SQL语句。

declare @sql varchar(8000)

set @sql = 'select id,sum(fileld1) from table1 where id in( ' + @id + ') group by id '

exec (@sql)

------解决方案--------------------
可以不用使用動態SQL語句,改用charindex


CREATE PROCEDURE test
@id nvarchar(500)
AS
begin
select id,sum(fileld1) from table1 where CharIndex( ', ' + Cast(id As Varchar) + ', ', ', ' + @id + ', ') > 0 group by id
end
GO
------解决方案--------------------
执行exec test '2,8 '报如下错误:
服务器: 消息 8114,级别 16,状态 5,过程 test,行 5
将数据类型 nvarchar 转换为 bigint 时出错。
但是执行exec test '2 '或者exec test '8 '都没问题。

------------------
呵呵,我現在看清楚了.當隻輸入 2 或 8 單個當有用了,輸入 '2,8 ',就不行了
要這樣寫

CREATE PROCEDURE test (@id nvarchar(500))
AS
begin
select id,sum(fileld1) from table1
where charindex( ', '+cast(id as nvarchar(10))+ ', ', ', '+@id+ ', ')> 0 group by id
end
GO



------解决方案--------------------
或者Like

CREATE PROCEDURE test
@id nvarchar(500)
AS
begin
select id,sum(fileld1) from table1 where ', ' + @id + ', ' Like '%, ' + Cast(id As Varchar) + ',% ' group by id
end
GO
------解决方案--------------------

动态sql语句基本语法
1 :普通SQL语句可以用Exec执行

eg: Select * from tableName
Exec( 'select * from tableName ')
Exec sp_executesql N 'select * from tableName ' -- 请注意字符串前一定要加N

2:字段名,表名,数据库名之类作为变量时,必须用动态SQL

eg:
declare @fname varchar(20)
set @fname = 'FiledName '
Select @fname from tableName -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。
Exec( 'select ' + @fname + ' from tableName ') -- 请注意 加号前后的 单引号的边上加空格

当然将字符串改成变量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName ' --设置字段名

declare @s varchar(1000)
set @s = 'select ' + @fname + ' from tableName '
Exec(@s) -- 成功
exec sp_executesql @s -- 此句会报错