|
条件:表格ABC,主键列为id int identity(1,1)
问题:从ABC中找出第m行至第n行的记录集(m<n)
在解答之前,先要弄清楚SQL的select语句中几个保留字(top,where,order)的执行顺序,
它们的执行顺序是 1.where 2.order 3.top 。弄清楚了这点,接下来就容易了。
解答一:
select top @n-@m+1 *
from ABC
where id not in (select top @m-1 id from ABC order by id)
order by id
解答二:
select A.* from
(select top @n-@m+1 B.*
from (select top @n * from ABC order by id) AS B
order by B.id desc) AS A
order by A.id
比较效率:解答二效率更高。
其他考虑:可以不限于主键列,可以针对任何一列排序。
根据上述两种解答,编写两个存储过程,输入参数为表名、列名、起始行号、终止行号。输出参数为整数,指示操作是否成功。存储过程返回一记录集。两存储过程在SQLServer2000上运行通过。
存储过程一:
CREATE PROCEDURE RetrieveRowsFromTable_A (
@ret int output,
@Table nvarchar(64),
@Column nvarchar(64),
@m int,
@n int
)
AS
DECLARE @error_var int, @rowcount_var int,@identity_var int
declare @sql nvarchar(4000)
declare @params nvarchar(500)
if (@m>@n)
begin
set @ret=-1
return
end
set @sql=N'select top ' + str(@n-@m+1) + N' * '
set @sql=@sql + N' from ' + @Table
set @sql=@sql + N' where ' + @Column + N' not in (select top ' + str(@m-1) + N' ' + @Column + N' from ' + @Table + N' order by ' + @Column + N')'
set @sql=@sql + N' order by ' + @Column
set @params=N'@Table nvarchar(64),@Column nvarchar(64),@m int,@n int'
EXEC sp_executesql @sql,@params,@Table,@Column,@m,@n
SELECT @error_var = @@ERROR, @rowcount_var = @@ROWCOUNT,@identity_var = @@IDENTITY
if (@error_var=0)
set @ret=@rowcount_var
else
set @ret=-1
GO
存储过程二:
CREATE PROCEDURE RetrieveRowsFromTable_B (
@ret int output,
@Table nvarchar(64),
@Column nvarchar(64),
@m int,
@n int
)
AS
DECLARE @error_var int, @rowcount_var int,@identity_var int
declare @sql nvarchar(4000)
declare @params nvarchar(500)
if (@m>@n)
begin
set @ret=-1
return
end
set @sql=N'select A.* from'
set @sql=@sql + N' (select top ' + str(@n-@m+1) + N' B.*'
set @sql=@sql + N' from (select top ' + str(@n) + N' * from ' + @Table + N' order by ' + @Column + N') AS B'
set @sql=@sql + N' order by B.' + @Column + N' desc) AS A'
set @sql=@sql + N' order by A.' + @Column
set @params=N'@Table nvarchar(64),@Column nvarchar(64),@m int,@n int'
EXEC sp_executesql @sql,@params,@Table,@Column,@m,@n
SELECT @error_var = @@ERROR, @rowcount_var = @@ROWCOUNT,@identity_var = @@IDENTITY
if (@error_var=0)
set @ret=@rowcount_var
else
set @ret=-1
GO
——End.
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=389587 |
|