2017-06-15 88 views
-3

如何在SQL Developer 2012中使用while循环使其成为可能?SQL Server while循环插入不同的行

如果一个值高于1,000,000(一百万)将其分成几行。

例如,如果值为2,400,000,则它将在三行中具有如下表2所示的下列值900,000,900,000和600,000。

表1

ID | Value 
1 | 200,000 
2 | 300,000 
3 | 1,000,000 
4 | 2,400,000 

表2

ID | Value 
1 | 200,000 
2 | 300,000 
3 | 1,000,000 
4 | 900,0000 
4 | 900,0000 
4 | 600,0000 
+0

请不要使用不适用于您的问题标签。 –

+0

不明确。什么价值?显示样本数据和期望的结果。 –

+0

900,000,900,000和600,000来自哪里? –

回答

0
if object_id('tempdb..#test','U') is not null 
    drop table #test 

create table #test (vals int) 
insert into #test values (600000),(800000), (2400000) 

declare @count int =0 -- psuedo group counter 
declare @i int -- used to contain current row value 

declare @prevval int -- used to step through values in table 
declare @more int = 1 -- used to create infinite while 

-- get the first value into @i 
select top 1 @i= vals from #test order by vals 

while @more = 1 
begin 
    set @prevval = @i 
    select @count += 1 
    while (@i - 900000)>0 
    begin 

     select @i -= 900000 
     select @count,900000 

    end 

     select @count, @i 

     select top 1 @i=vals 
     from #test 
     where vals > @prevval 
     order by vals 

     if @@rowcount =0 -- no more data... 
      break 
end