日期:2014-05-17  浏览次数:20584 次

如何循环建立几个表格
是这样的,我有一个数据库,我要把里面的数据分成几部分,然后放到不同表格中,想用循环语句来建立表格!
具体如下:
表名就用@str 中表示的来表示,如何加入到红色标记的代码?????那里,就是?????那里要怎么写

declare @x int,@str varchar(20)
set @x=0
while @x<20
begin
set @x=@x+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]<=@x
UNION
select * ,0,1 FROM RECORDCD4
WHERE [YEAR]>@x
) y
end

------解决方案--------------------
SQL code

-->try
declare @x int,@str varchar(20),@sql varchar(max)
set @x=0
while @x<20
begin
    set @x=@x+1
    set @str='按年分层 >'+cast(@x-1 as varchar(2))+'& <='+cast(@x as varchar(2))+'表'
    set @sql=isnull(@sql,'')+' select * into [数据库2].dbo.'+@str+' 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=0
while @x<20
begin
    set @x=@x+1
    set @str='[按年分层 >'+cast(@x-1 as varchar(2))+'& <='+cast(@x as varchar(2))+'表]'
    SET @sql='select * into [数据库2].dbo.'+@str+' 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