如何从表中选择行乘以n?

时间:2012-06-06 14:21:53

标签: sql-server tsql select union

我有一个选择电台,如下所示,返回2行:

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。

我希望问题清楚。

1 个答案:

答案 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;