2017-06-15 41 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