以下是一个SQL 2005 的分页查询脚本,但是运行的时候报错,请大家帮我看看
DECLARE @total_pages AS INTEGER
DECLARE @start_item AS INTEGER
DECLARE @items_count AS INTEGER
DECLARE @rows_per_page AS INTEGER
DECLARE @current_page AS INTEGER
DECLARE @Table VARCHAR(128)
DECLARE @SQL VARCHAR(8000)
SET @SQL='SELECT '+@total_pages+' = COUNT(*) /'+ @rows_per_page + '1,'
SET @SQL=@SQL+@items_count+'= COUNT(*)'
SET @SQL=@SQL+'FROM '+@Table+';'
SET @SQL=@SQL+'SET '+@start_item+' = '+@rows_per_page+' * ('+@current_page+' - 1)'
SET @SQL=@SQL+' select * from '
SET @SQL=@SQL+' ('
SET @SQL=@SQL+' select ROW_NUMBER() OVER (order by ID) as item'
SET @SQL=@SQL+' ,'+@items_count+' AS items_count'
SET @SQL=@SQL+' ,'+@current_page+' AS current_page'
SET @SQL=@SQL+' ,'+@total_pages+' AS total_pages'
SET @SQL=@SQL+' ,* from'+@Table
SET @SQL=@SQL+' ) as T '
SET @SQL=@SQL+' where T.item >= '+@start_item+'+ 1 '
SET @SQL=@SQL+' AND T.item <= '+@start_item + @rows_per_page
Exec(@SQL)
这段代码是存贮过程里的代码,执行时,提示:
消息 245,级别 16,状态 1,第 11 行
在将 varchar 值 'SELECT ' 转换成数据类型 int 时失败。
你的动态SQL有错,先给你基本语法.
--动态sql语句基本语法
- SQL code
-
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 -- 此句会报错
declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正确
3. 输出参数
declare @num int,
@sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)
--如何将exec执行结果放入变量中?
declare @num int,
@sqls nvarchar(4000)
set @sqls='select @a=count(*) from tableName '
exec sp_executesql @sqls,N'@a int output',@num output
select @num
DECLARE @rows_per_page AS INTEGER
DECLARE @current_page AS INTEGER
DECLARE @total_pages AS INTEGER
DECLARE @start_item AS INTEGER
DECLARE @items_count AS INTEGER
-- 设置每页的行数
SET @rows_per_page = 10
-- 设置要显示的页号(从1开始)
SET @current_page = 1
SELECT @total_pages = COUNT(*) / @rows_per_page + 1,
@items_count= COUNT(*)
FROM ASN_Details;--表名(这是修改的地方)
--计算此页中从第几个开始显示
SET @start_item = @rows_per_page * (@current_page - 1)
select * from
(
select ROW_NUMBER() OVER (order by ID) as item--用什么排序(返回正在显示第几条)
,@items_count AS items_count --一共有多少条
,@current_page AS current_page --当前页
,@total_pages AS total_pages --一共多少页
,* from ASN_Details--表名(这是修改的地方)
) as T
where T.item >= @start_item + 1
AND T.item <= @start_item + @rows_per_page
这是SQL脚本,要求是表名要动态传入,其他不变,可以获取指定页等
本文提供了一个SQL Server 2005分页查询脚本的修复方案,解决了动态SQL语法错误的问题,并给出了正确的动态SQL使用示例。

1134

被折叠的 条评论
为什么被折叠?



