1个记录为多个记录

时间:2018-08-27 12:29:06

标签: sql

如果我的表格为

ID  NAME   PHNO
1   xyz    7895632147
2   abc    8795412632
3   def    9587412306

我希望输出为

ID    NAME    PHNO
1     xyz      7895632147
1     xyz      7895632147
1     xyz      7895632147
1     xyz      7895632147
1     xyz      7895632147
2     abc     8795412632
2     abc     8795412632
2     abc     8795412632
2     abc     8795412632
2     abc     8795412632
3     def     9587412306
3     def     9587412306
3     def     9587412306
3     def     9587412306
3     def     9587412306

我需要动态地多次执行它,这里以5次为例。

如何在Microsoft SQL Server Management Studio中做到这一点?

2 个答案:

答案 0 :(得分:3)

使用recursive CTE执行此操作:

declare @terminator int = 5;

with recursivecte as (
select ID,name,phno ,1 as n from testtable
union all
select ID,name,phno, n +1 from recursivecte

where N < @terminator
)
select * from recursivecte

答案 1 :(得分:1)

使用MySQL,为此目的保留一个预建表“ tally”(它可能只有10条记录,您可以根据需要使用笛卡尔联接来增加它们的记录,或者您可以使用其中一个系统表):

create table tally (i int);
insert into tally (i)
values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10); 

然后您需要的是交叉联接:

select t1.Id, t1.Name, t1.Phno
from myTable t1
cross join (select * from tally limit 5) t
order by t1.Id;

这里是SQLFiddle demo.

该问题最初是MySQL!

使用MS SQL Server更加容易:

with tally as
(
  select top(5) row_number() over (order by t1.object_id) as N
  from sys.all_columns t1 
  cross join sys.all_columns t2
)
select t1.Id, t1.Name, t1.Phno
from myTable t1
cross join tally
order by t1.Id;

这是SQLFiddle demo.