我想根据传入的表名查询表里相应数据,这种写法报错,请问需要怎样修改?谢谢。。。。
Create PROCEDURE ALLGetPageDataOutRowPageCount
(
@PageIndex int = 1,--当前页数
@PageSize int = 4,--每页大小
@NowPage int = 1,--根据传入栏目id要加载当前页的数据
@NowTable NVARCHAR(50) = N'table',--当前传入表名
@RowCount int output,--总行数(传出参数)
@PageCount int output--总页数(传出参数)
)
AS
begin
DECLARE @sql NVARCHAR(max),@sqlCount NVARCHAR(225)
select @RowCount =COUNT(FChildId),@PageCount=CEILING((COUNT(FChildId)+0.0)/@PageSize) FROM @NowTable where FParentsId=@NowPage
SET @sql='SELECT TOP '+LTRIM(str(@PageSize))+' * FROM '+@NowTable+' where FParentsId='+LTRIM(str(@NowPage))+' and FChildId not in(select top '+LTRIM(str((@PageIndex-1)*@PageSize))+' FChildId from '+@NowTable+' where FParentsId='+LTRIM(str(@NowPage))+' order by FImagIndex desc,FImageUpTime desc)order by FImagIndex desc, FImageUpTime desc'
print @sql
EXEC(@sql)
end
报错为{消息 1087,级别 15,状态 2,过程 ALLGetPageDataOutRowPageCount,第 13 行
必须声明表变量 "@NowTable"。}
是说你这句也要使用EXEC执行吧。
select @RowCount =COUNT(FChildId),@PageCount=CEILING((COUNT(FChildId)+0.0)/@PageSize) FROM @NowTable where FParentsId=@NowPage
比如
Set @sql1='select @RowCount =COUNT(FChildId),@PageCount=CEILING((COUNT(FChildId)+0.0)/@PageSize) FROM '+@NowTable+' where FParentsId=@NowPage';
EXEC(@sql1);
这样写我怎么给@RowCount 赋值呢?难道只能用字符串拼接??谢谢。。。
@~峰~:
拼接 或者 参考下面示例:
CREATE PROCEDURE PROC_Login_executesql( @userNamenvarchar(10), @password nvarchar(10), @count int OUTPUT ) AS BEGIN DECLARE @s nvarchar(1000); set @s=N'SELECT @count=COUNT(*) FROM Login WHERE UserName=@userName AND Password=@password'; EXEC sp_executesql @s,N'@userName nvarchar(10),@password nvarchar(10),@count int output',@userName=@userName,@password=@password,@count=@count output END
exec sp_executesql @sql,N'@RowCount int OUT',@RowCount OUT
笨方法,你如果很清楚 @NowTable 的列数,假设为3列,可以用字符串拼接啊,在获取Table 后从第一行取出数据,再把第一行删除掉就是你要的数据了,这样免去了你修改参数的麻烦
Create PROCEDURE ALLGetPageDataOutRowPageCount ( @PageIndex int = 1,--当前页数 @PageSize int = 4,--每页大小 @NowPage int = 1,--根据传入栏目id要加载当前页的数据 @NowTable NVARCHAR(50) = N'table'--当前传入表名 ) AS begin DECLARE @sql NVARCHAR(max),@sqlCount NVARCHAR(225) select @sql=' select COUNT(FChildId),CEILING((COUNT(FChildId)+0.0)/('+@PageSize+')),'''' FROM @NowTable where FParentsId=@NowPage union all SELECT TOP '+LTRIM(str(@PageSize))+' * FROM '+@NowTable+' where FParentsId='+LTRIM(str(@NowPage))+' and FChildId not in(select top '+LTRIM(str((@PageIndex-1)*@PageSize))+' FChildId from '+@NowTable+' where FParentsId='+LTRIM(str(@NowPage))+' order by FImagIndex desc,FImageUpTime desc)order by FImagIndex desc, FImageUpTime desc' EXEC sp_executesql @sql end