编写的MS-SQL 存储过程出了问题,请大家帮帮忙!
ALTER PROCEDURE pageData
-- Add the parameters for the stored procedure here
@sqlStr varchar(300),
@pageSize int = 10,
@objectPage int = 1,
@pk varchar(50) = 'id',
@sortPro varchar(50) = null,
@sortType varchar(4) = null
AS
BEGIN
declare @cntSqlStr varchar(300)
, @count int
set @cntSqlStr='select @count = count('+@pk+')'+ substring(@sqlStr,Patindex('%from%',@sqlStr),len(@sqlStr)+1)
exec(@cntSqlStr)
if (@count%@pageSize)=0
begin
if @objectPage >(@count/@pageSize)
begin
set @objectPage=(@count/@pageSize)
end
end
else
begin
if @objectPage >((@count/@pageSize)+1)
begin
set @objectPage=((@count/@pageSize)+1)
end
end
set @sqlStr= 'select top('+convert(varchar,@pageSize)+')'+substring(@sqlStr,7,len(@sqlStr)+1)
if patindex('%group by%',@sqlStr)>=1
begin
if patindex('%having%',@sqlStr)>=1
begin
set @sqlStr = @sqlStr+' and '
end
else
begin
set @sqlStr = @sqlStr+' having '
end
end
else if patindex('%where%',@sqlStr)>=1
begin
set @sqlStr = @sqlStr+' and '
end
else
begin
set @sqlStr = @sqlStr+' where '
end
set @sqlStr =@sqlStr+' id not in(select top('+convert(varchar,@pageSize)+'*('+convert(varchar,@objectPage)+'-1)) id from table ) '
if @sortPro is null
begin
set @sqlStr = @sqlStr+' order by '+@sortPro+' '+@sortType
end
select @sqlStr
END
GO
exec pageData 'select * from attributes',1,1,'id'
具体代码如上,当执行后 会 报出消息
消息 137,级别 15,状态 1,第 1 行
必须声明标量变量 "@count"。
(1 行受影响)
但是代码中,可以看到@count 已经声明了啊!
存储过程
标量变量
------解决方案--------------------用这个
ALTER PROCEDURE pageData
-- Add the parameters for the stored procedure here
@sqlStr varchar(300),
@pageSize int = 10,
@objectPage int = 1,
@pk varchar(50) = 'id',
@sortPro varchar(50) = null,
@sortType varchar(4) = null
AS
BEGIN
declare @cntSqlStr varchar(300)
, @count int
set @cntSqlStr='select '+@count+' = count('+@pk+')'+ substring(@sqlStr,Patindex('%from%',@sqlStr),len(@sqlStr)+1)
exec(@cntSqlStr)
if (@count%@pageSize)=0
begin
if @objectPage >(@count/@pageSize)
begin
set @objectPage=(@count/@pageSize)
end
end
else
begin
if @objectPage >((@count/@pageSize)+1)
begin
set @objectPage=((@count/@pageSize)+1)
end
end
set @sqlStr= 'select top('+convert(varchar,@pageSize)+')'+substring(@sqlStr,7,len(@sqlStr)+1)
if&