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

存储过程生疏,还望指教
CREATE PROCEDURE insert_single_selected_two
@word varchar(10),
@grade varchar(10),
@user_name varchar(40),
@number numeric(10,0)
AS
begin
set @user_name=@user_name+'_single_selected'
insert into @user_name
select top @number * from single_select 
where 级别=@grade and 关键字=@word
and id not in (select id from @user_name) order by newid()
end
RETURN

直接报错:@number附近有错
@number就两个地方,偶想不到哪里出的错。
顺便再问问,where条件中的“级别=@grade and 关键字=@word”是不是有效的?我担心的是会不会因为没有单引号而导致出错

------解决方案--------------------
SQL code

CREATE PROCEDURE insert_single_selected_two
@word varchar(10),
@grade varchar(10),
@user_name varchar(40),
@number numeric(10,0)
AS
begin
declare @str varchar(2000)
set @str=''
set @user_name=@user_name+'_single_selected'
set @str=
'insert into '+@user_name+
'select top '+ltrim(@number)+ ' * from single_select 
where 级别=@grade and 关键字=@word+ 
and id not in (select id from '+@user_name+') order by newid()
end'
exec(@str)
RETURN
存储过程中要想传入表名的时候不能直接使用,你得先把语句拼接起来,然后动态执行

------解决方案--------------------
当表名为动态时,需要使用动态SQL.
SQL code
CREATE PROCEDURE insert_single_selected_two
@word varchar(10),
@grade varchar(10),
@user_name varchar(40),
@number numeric(10,0)
AS
begin
set @user_name=@user_name+'_single_selected'
declare @sql as varchar(1000)
set @sql = '
insert into ' + @user_name + '
select top ' + ltrim(@number) + ' * from single_select  
where 级别=''' + @grade + ''' and 关键字= ''' + @word + '''
and id not in (select id from ' + @user_name + ') order by newid()'
exec(@sql)
end
RETURN