日期:2014-05-18  浏览次数:20555 次

【求助】求一SQL脚本实现如下功能,请大虾进来帮忙。
数据表内容有如:
字段         Start             End
                  4                     9

要求写一个SQL脚本得出如下结果:
  4
  5
  6
  7
  8
  9

我写了一个觉得效率不高。

declare   @Start   int
declare   @End   int
select   @Start=[Start],
              @End=[End]   from   tb1


while   @Start <=@End
begin
    print(@Start)
    set   @Start=@Start+1
end

------解决方案--------------------
declare @Start int
declare @End int
select @Start=4,@End=9
declare @sql varchar(200)
set @sql= 'select top '+rtrim(@End-@Start+1)+ ' id=identity(int, '+rtrim(@Start)+ ',1) into #t from sysobjects,syscolumns '+char(13)+ 'select * from #t '
exec(@sql)
/*
(所影响的行数为 6 行)

id
-----------
4
5
6
7
8
9
*/
------解决方案--------------------
--試下这个:

select top 1000 id=identity(int,1,1) into #t from syscolumns a ,syscolumns b

select * from #t where id between 4 and 9

drop table #t
------解决方案--------------------
create table aa(start1 int,end1 int)
insert into aa values (1,7)
insert into aa values (3,9)
select * from aa
declare @min int ,@max int
declare @i int
select @min=min(start1),@max=max(end1) from aa
declare @table table
(id int,num int)
set @i=@min
while @i <=@max
begin
insert into @table select @i,sum(case when @i> =start1 and @i <=end1 then 1 else 0 end) from aa
set @i=@i+1
end
select * from @table
drop table aa
------解决方案--------------------
drop table #t
go
create table #t(Start int,[End] int)
insert into #t
select 1,7
union all select 3,9

declare @Start int
declare @End int
select @Start=min(Start),@End=max([End]) from #t
declare @sql varchar(200)
set @sql= 'drop table tb '+char(13)+ 'select top '+rtrim(@End-@Start+1)+ ' id=identity(int, '+rtrim(@Start)+ ',1) into tb from sysobjects,syscolumns '+char(13)
exec(@sql)

select id,(select count(*) from #t where id between Start and [End]) as qty
from tb
/*
id qty
----------- -----------
1 1
2 1
3 2
4 2
5 2
6 2
7 2
8 1
9 1

(所影响的行数为 9 行)
*/