当前位置: 代码迷 >> Sql Server >> 怎么循环建立几个表格
  详细解决方案

怎么循环建立几个表格

热度:2   发布时间:2016-04-27 11:20:02.0
如何循环建立几个表格
是这样的,我有一个数据库,我要把里面的数据分成几部分,然后放到不同表格中,想用循环语句来建立表格!
具体如下:
[email protected] 中表示的来表示,如何加入到红色标记的代码?????那里,就是?????那里要怎么写

declare @x int,@str varchar(20)
set @x=0
while @x<20
begin
set @[email protected]+1
set @str='按年分层 >'+cast(@x-1 as varchar(2))+'& <='+cast(@x as varchar(2))+'表'
select * into [数据库2].dbo.????? from
(
select *,status status2,[YEAR]-(@x-1) year2 FROM RECORDCD4
WHERE [YEAR]>@x-1 and [YEAR]<[email protected]
UNION
select * ,0,1 FROM RECORDCD4
WHERE [YEAR]>@x
) y
end

------解决方案--------------------
SQL code
-->trydeclare @x int,@str varchar(20),@sql varchar(max)set @x=0while @x<20begin    set @[email protected]+1    set @str='按年分层 >'+cast(@x-1 as varchar(2))+'& <='+cast(@x as varchar(2))+'表'    set @sql=isnull(@sql,'')+' select * into [数据库2].[email protected]+' from    (    select *,status status2,[YEAR]-'+cast((@x-1) as varchar(5))+' year2 FROM RECORDCD4    WHERE [YEAR]>'+cast((@x-1) as varchar(5))+' and [YEAR]<='+cast(@x as varchar(5))+'    UNION    select * ,0,1 FROM RECORDCD4    WHERE [YEAR]>'+cast(@x as varchar(5))+'    ) y'end exec(@sql)
------解决方案--------------------
楼上正解
------解决方案--------------------
SQL code
declare @x int,@str varchar(20),@sql VARCHAR(max)set @x=0while @x<20begin    set @[email protected]+1    set @str='[按年分层 >'+cast(@x-1 as varchar(2))+'& <='+cast(@x as varchar(2))+'表]'    SET @sql='select * into [数据库2].[email protected]+' from    (    select *,status status2,[YEAR]-('+LTRIM(@x-1)+') year2 FROM RECORDCD4    WHERE [YEAR]>'+LTRIM(@x-1)+' and [YEAR]<='+LTRIM(@x)+'    UNION    select * ,0,1 FROM RECORDCD4    WHERE [YEAR]>'+LTRIM(@x)+'    ) y'    PRINT @sql    --EXEC (@sql)END
  相关解决方案