2012-06-06 45 views
1

我有一個選擇站如下它返回2行:(的實際查詢是相當大的,並返回更加行,但爲了簡單起見,假設在上述)如何從表中選擇行乘以n?

select ID, Title from TableName 

我需要一個查詢哪些返回更多的數據,我不能更改數據庫表。

如何乘以/複製並增加由例如返回的行數。 5次,以便返回10行?

我知道與UNION ALL這是可能的,如果我把它寫5次:

select ID, Title from TableName 
UNION ALL 
select ID, Title from TableName 
UNION ALL 
select ID, Title from TableName 
UNION ALL 
select ID, Title from TableName 
UNION ALL 
select ID, Title from TableName 

但有沒有其他更簡單的方法?我的實際查詢更大,因此不能使用UNION ALL。

我希望問題清楚。

+0

爲什麼你需要你的行返回各5次? –

+0

需要更多數據。 –

回答

2
DECLARE @i INT; 

SET @i = 1000; 

;WITH n AS (SELECT TOP (@i) object_id FROM sys.all_columns) 
SELECT t.ID, t.Title FROM TableName AS t CROSS JOIN n; 

如果您發現CTE沒有提供足夠的行,您總是可以製作更多!

DECLARE @i INT; 

SET @i = 1000000; 

;WITH n AS 
(
    SELECT TOP (@i) c.object_id FROM sys.all_columns AS c 
    CROSS JOIN sys.all_objects AS o 
) 
SELECT t.ID, t.Title FROM TableName AS t CROSS JOIN n; 

...或者你可以創建自己的Numbers表格:

SET NOCOUNT ON; 

DECLARE @UpperLimit INT = 1000000; -- customize this 

;WITH n AS 
(
    SELECT 
     x = ROW_NUMBER() OVER (ORDER BY s1.[object_id]) 
    FROM  sys.all_objects AS s1 
    CROSS JOIN sys.all_objects AS s2 
    CROSS JOIN sys.all_objects AS s3 
) 
SELECT Number = x 
    INTO dbo.Numbers 
    FROM n 
    WHERE x BETWEEN 1 AND @UpperLimit; 

GO 
CREATE UNIQUE CLUSTERED INDEX n ON dbo.Numbers(Number) 
    -- if Enterprise Edition: 
    -- WITH (DATA_COMPRESSION = PAGE) 
; 

現在你的查詢可以是:

DECLARE @i INT; 

SET @i = 1000000; 

;WITH n AS (SELECT TOP (@i) Number FROM dbo.Numbers) 
SELECT t.ID, t.Title FROM TableName AS t CROSS JOIN n;