在SQl 2008中使用Select重复录制

时间:2013-03-08 12:44:29

标签: sql

声明@NoofRept int

从tbl_Name中选择id,Name,其中id = 1

id  |Name
1   |XXXXXXX

我的要求 重复此记录@NoofRept时间

id  |Name
1   |XXXXXXX
1   |XXXXXXX
1   |XXXXXXX
1   |XXXXXXX

2 个答案:

答案 0 :(得分:0)

如果你想重复小于2047的记录你可以使用表Master..spt_values,这是一个系统表,P类型的序号从0到2047:

DECLARE @NoofRept INT = 10

SELECT  t.ID, t.Name
FROM    tbl_Name t
        CROSS JOIN Master..spt_Values v
WHERE   t.ID = 1
AND     v.Type = 'P'
AND     v.Number BETWEEN 1 AND @NoofRept

<强> Example on SQL Fiddle

如果您需要更多,那么您需要CROSS JOIN个表来获取所需的行数:

SELECT  ID, Name
FROM    tbl_Name
        CROSS JOIN 
        (   SELECT  rpt = ROW_NUMBER() OVER(ORDER BY a.Number)
            FROM    Master..spt_Values a
                    CROSS JOIN Master..spt_Values b
                    --CROSS JOIN Master..spt_values c
                    --CROSS JOIN Master..spt_values d
        ) v
WHERE   ID = 1
AND     v.rpt BETWEEN 1 AND @NoofRept

根据需要取消注释联接

<强> Example on SQL Fiddle

答案 1 :(得分:0)

未经测试的伪代码,但这样的事情可能会起到作用:

DECLARE @sql nvarchar(max);
DELCARE @i int; 
SET @i = 1;

SET @sql = 'select id,Name from tbl_Name where id=1'

WHILE @i < @NoofRept
BEGIN
  SET @sql = @sql + 'UNION select id,Name from tbl_Name where id=1'

  SET @i = @i + 1;
END

EXEC sp_executesql @sql;