向各位大虾请教一个问题。一个表中有1000行数据,我想第一次选择1——100行,第二次选择101--200行,...。请问如何写SQL语句。

解决方案 »

  1.   

    N-M条记录
    1.
    select top m * into 临时表(或表变量) from tablename order by columnname -- 将top m笔插入
    set rowcount n
    select * from 表变量 order by columnname desc
    2.
    select top n * from 
    (select top m * from tablename order by columnname) a
    order by columnname desc
    3.
    如果tablename里没有其他identity列,那么:
    select identity(int) id0,* into #temp from tablename取n到m条的语句为:
    select * from #temp where id0 >=n and id0 <= m如果你在执行select identity(int) id0,* into #temp from tablename这条语句的时候报错,那是因为你的DB中间的select into/bulkcopy属性没有打开要先执行:
    exec sp_dboption 你的DB名字,'select into/bulkcopy',true
    4.
    如果表里有identity属性,那么简单:
    select * from tablename where identitycol between n and m
      

  2.   

    2.
    select top n * from 
    (select top m * from tablename order by columnname) a
    order by columnname desc
    改为
    查询第n 到第m条记录
    2.
    select top m-n * from 
    (select top m * from tablename order by columnname) a
    order by columnname desc
      

  3.   

    create table tab(id int primary key(id))
    declare @int int
    SET @int=1
    while @int<1000
    begin
    insert into tab(id)
    select @int
    SET @int=@int+1
    end
    declare @i int--检索次数
    DECLARE @j int
    SET @i=2
    SET @i=@i*100
    SET @j=@i-100
    DECLARE @sql Varchar(1000)
    SET @sql='
    select top 100 * from tab
    where id not in (select top '+cast(@j as varchar)+' id from tab)'
    print @sql
    exec(@sql)
    drop table tab
      

  4.   

    select top 100 * from tab
    where id not in (select top 100 id from tab)
    id
    -----------
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200(100 行受影响)