在SQL server中进行一个循环查询,将每次的查询结果存入不同表中,
程序如下:useseattledeclare@iintset@i=1declare@accmilefloatdeclare@milefloatdeclaremcursor...
程序如下:use seattle
declare @i int
set @i=1
declare @accmile float
declare @mile float
declare m cursor
for (select Milepost from lianxiacc)
open m
fetch next from m into @accmile
while @@FETCH_STATUS = 0
begin
set @mile=(select max(milepost)from i5_2011_Jan where milepost<@accmile)
select * into sample@i from i5_2011_Jan
where Milepost=@mile
set @i = @i+1
fetch next from m into @accmile
end
其中 select * into sample@i from i5_2011_Jan 这一句里怎么实现每次循环自动更改表名?
求大神指点~
我这个把变量@i直接放上去的方法根本就是错的 展开
declare @i int
set @i=1
declare @accmile float
declare @mile float
declare m cursor
for (select Milepost from lianxiacc)
open m
fetch next from m into @accmile
while @@FETCH_STATUS = 0
begin
set @mile=(select max(milepost)from i5_2011_Jan where milepost<@accmile)
select * into sample@i from i5_2011_Jan
where Milepost=@mile
set @i = @i+1
fetch next from m into @accmile
end
其中 select * into sample@i from i5_2011_Jan 这一句里怎么实现每次循环自动更改表名?
求大神指点~
我这个把变量@i直接放上去的方法根本就是错的 展开
1个回答
展开全部
表名不能是变量,你可以用动态SQL语句来实现
use seattle
declare @i int
set @i=1
declare @accmile float
declare @mile float
declare @strsql nvarchar(4000)
declare m cursor
for (select Milepost from lianxiacc)
open m
fetch next from m into @accmile
while @@FETCH_STATUS = 0
begin
set @mile=(select max(milepost)from i5_2011_Jan where milepost<@accmile)
set @strsql='select * into sample'+cast(@i as varchar(20))+' from i5_2011_Jan where Milepost='+cast(@mile as varchar(50))
exec(@strsql)
set @i = @i+1
fetch next from m into @accmile
end
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询