在SQL中,如何构建一个复制行次数的循环

时间:2015-08-14 14:43:22

标签: sql

有人可以帮忙吗?我的起始表看起来像2个字段:

Name    Counter
dave    2
Joe     3

我希望我的结果看起来像这样:

Name    Counter
dave    1
dave    2
joe     1
joe     2
joe     3 

基本上在计数器上创建n个记录并从1开始。我尝试使用计数器作为变量进行循环,但代码只是运行不间断..有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

您可以使用数字表或以下技巧使用系统视图来构建序列:

WITH Nums AS
(
  SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id]) 
  FROM sys.all_objects 

)
SELECT Name, Counter = n
FROM Nums n CROSS JOIN Table1 t1
WHERE n BETWEEN 1 AND Counter
ORDER BY Name, Counter;

Demo

此视图只有大约2000行,因此如果您需要更多行,则可以使用数字表。

http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1

(假定SQL-Server)

答案 1 :(得分:0)

程序SQL Server解决方案:

declare @input table
(
  name nvarchar(100)
 ,wantedrows int
 ,processed bit
 ,id uniqueidentifier
);

declare @output table
(
  name nvarchar(100)
 ,rownum int
);

insert into @input
select 'Dave',3,0,newid()
union
select 'Joe',2,0,newid();

while exists(select * from @input where processed = 0)
begin
  declare @currentid uniqueidentifier = (select top 1 id from @input where processed = 0);
  declare @currentwantedrows int = (select wantedrows from @input where id = @currentid);
  declare @i int = 0;
  while @i < @currentwantedrows
  begin
    insert into @output
    select name,@i+1
    from @input
    where id = @currentid;
    set @i = @i + 1;
  end;
  update @input set processed = 1 where id = @currentid;
end

select name,wantedrows from @input;
select * from @output;

答案 2 :(得分:0)

足够百份?

create table #c (num)

insert into #c (num)
select 0 union
select 1 union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9

select T.Name,  c1.num * 10 + c0.num + 1
from T, #c c1, #c c0
where c1.num * 10 + c0.num < T.Counter

drop table #c

您没有说出哪个版本的Sybase。我工作过的旧版本没有允许派生表,所以我不得不将值抛出到临时表中。但你可以看到如何扩展这个想法。如果这是你不止一次需要做的事情,这可能不是最好的方法。