您现在的位置是:首页 >

数据库实现分页查询 为数据库的表自动生成行号----为分页打好基础

火烧 2021-10-24 23:01:15 1073
为数据库的表自动生成行号----为分页打好基础   在以数据库为基础的应用程序开发中 分页是一个比较常用的操作 可惜的是SQL Server 中没有Oracle中相应的ROWNUM属性可用 用 触发器

为数据库的表自动生成行号----为分页打好基础  

  在以数据库为基础的应用程序开发中 分页是一个比较常用的操作 可惜的是SQL Server 中没有Oracle中相应的ROWNUM属性可用 用 触发器 生成一个ROWNUM列]勉强可以一用 当然用如下的SQL语句也可以生成第i页 每页n行 tid是主键列 select top n  * from tab  where strWhere  and  tid>(select max(tid)                                           from (select top (i )*n  tid from tab  where  strWhere  order by tid ) as T)                                         )order by tid也可以 但是我想用另一种方法也未尝不可因此就有自动生成ROWNUM列的想法eg:     建表 CREATE TABLE [dbo] [orderEmp] ( [rownum] [int] NOT NULL 同时该列要求有唯一性约束 [ordID] [int] IDENTITY ( ) NOT NULL 主键列 [empID] [int] NOT NULL  [empTxt] [varchar] ( ) COLLATE Chinese_PRC_CI_AS NOT NULL  [empDate] [datetime] NOT NULL 此列上建 聚集索引 ) ON [PRIMARY] 对插入语句处理的触发器CREATE  TRIGGER orderEmpAddTrgON  orderEmpinstead of   INSERTASbegin    declare  @rw int    select  @rw=     select @rw=max(rownum) from orderEmp    if(@rw is null)         select @rw=     select  @rw=@rw+   INSERT INTO orderEmp(rownum empID empTxt empDate)  SELECT @rw i empID i empTxt i empDate  FROM inserted  i end

数据库实现分页查询 为数据库的表自动生成行号----为分页打好基础

   删除的 触发器 CREATE TRIGGER orderEmpDelTrgON dbo orderEmpFOR  DELETEASbegin    set nocount on    declare  @rw int    declare   @tab table(rw int)    insert into @tab    select   rownum from deleted    order by rownum desc  不可以掉 至于为什么 大家自己试试就知道了    declare  cp cursor     for     select   rw from @tab     open cp     fetch next from cp into  @rw     while  @@fetch_status=       begin         update    orderEmp          set        rownum=rownum          where     rownum>@rw         fetch next from cp into @rw      end    close  cp    deallocate cp    set nocount offend 这个触发器是为屏掉用户直接从SQL企业管理器 打开表后对表中的ROWNUM列进行修改 可能不完全 但是通过UPdate语句操作表的时 只要不修改rownum列是不会出现问题的CREATE TRIGGER orderEmpUpdTrgON orderEmpFOR  UPDATE AS  begin  IF UPDATE (rownum)     RAISERROR ( ROWNUM列不可以自行修改! )  ROLLBACK TRANSACTION

  end   添加新记录的存储过程如下 create    PROCEDURE [addOrderEmp] ( @empID  [int]   @empTxt  [varchar]( )   @empDate  [datetime])

  AS INSERT INTO [orderEmp]   (  [rownum]   [empID]   [empTxt]   [empDate])  VALUES  (          @empID   @empTxt   @empDate) 是一定要的但是不会影响ROWNUM列 只是为了占用内存而已下面是我的测试用例:

  insert into orderemp(rownum empid emptxt empdate)values( ddfdd getdate())insert into orderemp(rownum empid emptxt empdate)values( ddfdd getdate())insert into orderemp(rownum empid emptxt empdate)values( ddfdd getdate())insert into orderemp(rownum empid emptxt empdate)values( ddfdd getdate())insert into orderemp(rownum empid emptxt empdate)values( ddfdd getdate())select    * from orderemp  order by rownumdelete from  orderemp where   empid> and empid< select    * from orderemp  order by rownum至于更新的语句吗只要不更新ROWNUM列 就不用处理了

lishixinzhi/Article/program/Oracle/201311/16686  
永远跟党走
  • 如果你觉得本站很棒,可以通过扫码支付打赏哦!

    • 微信收款码
    • 支付宝收款码