2013-03-08 173 views
0

申報@NoofRept詮釋重複記錄與選擇的SQL 2008

選擇ID,名稱來自tbl_Name其中id = 1

id |Name 
1 |XXXXXXX 

我的要求這個 重複這個記錄@NoofRept時間

id |Name 
1 |XXXXXXX 
1 |XXXXXXX 
1 |XXXXXXX 
1 |XXXXXXX 
+0

手段無論你在變量@NoofRept通過它應該給你錄製多少次? – DevelopmentIsMyPassion 2013-03-08 12:51:52

回答

0

如果你想重複小於最大值2047的記錄,你可以使用表Master..spt_values,這是一個系統表,而類型P有序列號RS從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

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;