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

存储过程里面怎么使用变量啊。
alter   procedure   p_ppp
        @tab   varchar(100),
        @num   int  
as
declare     @tmp1     table(articleID     int,nkey     varchar(100))
select   *   from   @tmp1   --这句没错
exec(N 'select   top   '+@num+ '   *   from   '+@tab)--这句也没错
exec(N 'select   top   '+@num+ '   *   from   @tmp1 ')--这句执行存储过程时出错,必须声明变量   '@tmp1 '
exec(N 'select   top   '+@num+ '   *   from   '+@tmp1)--这句创建存储过程时出错,必须声明变量   '@tmp1 '
go

我现在必须用组合语句,但是我这这两种写法都不能通过,我到底该怎么写呢??


我的目的就是能实现select   top   @num   from   @tmp1的效果,怎么写都不对。

------解决方案--------------------
alter PROCEDURE p_news_TagsUsedGet-- p_news_TagsUsedGet 125,10,1
@classid int,--分类id
@num int,--取的个数
@order varchar--排序方式(按标签被使用次数排序numused,或按标签被浏览次数排序hits)
as
create table ## (articleID int,nkey varchar(100))--返回表
declare @id int,@nkey varchar(100)
declare c cursor for
select articleID,nkey from article where classid=@classid
open c
fetch next from c into @id,@nkey
while @@fetch_status = 0
begin
WHILE CHARINDEX( ', ',@nkey)> 0
BEGIN
INSERT INTO ##(articleID,nkey) VALUES(@id,LEFT(@nkey,CHARINDEX( ', ',@nkey)-1))
SET @nkey=RIGHT(@nkey,LEN(@nkey)-CHARINDEX( ', ',@nkey))
END
INSERT INTO ##(articleID,nkey) VALUES(@id,@nkey)
fetch next from c into @id,@nkey
end
close c
deallocate c


declare @sql nvarchar(500)

truncate table T_Tag
set @sql=N 'insert into T_Tag(Tag,ArticleNum) select top '+convert(nvarchar,@num)+N ' nkey,[num]=count(articleID) from ## group by nkey order by num desc '
exec sp_executesql @sql
print @sql
select Tag,ArticleNum from T_Tag

drop table ##
--insert into T_Tag(Tag,ArticleNum) select top @num nkey,[num]=count(articleID) from @tmp1 group by nkey order by num desc
GO