一尘不染

创建基于sql视图的范围转换为行

sql

我有一个像这样的表

ColA|ColB|LowRange|HighRange
----------------------------
  1   A     1         5

我想创建一个视图,以下列格式提供数据

ColA|ColB|RangeNumber
----------------------
  1   A       1
  1   A       2 
  1   A       3
  1   A       4
  1   A       5

我对视图不够熟悉,所以我需要一些指导。

谢谢


阅读 136

收藏
2021-03-10

共1个答案

一尘不染

您可以使用递归CTE完成此操作

CREATE TABLE ranges (
    ColA int,
    ColB char,
    LowRange int,
    HighRange int,
);

INSERT INTO ranges
VALUES (1, 'A', 1, 5),
(2, 'B', 5, 10);
GO

CREATE VIEW range_view
AS
WITH each AS
(
    SELECT ColA, ColB, LowRange AS n, HighRange
      FROM ranges
    UNION ALL
    SELECT ColA, ColB, n + 1, HighRange
      FROM each
     WHERE n + 1 <= HighRange
)
SELECT ColA, ColB, n
FROM each
GO

SELECT * FROM range_view
DROP VIEW range_view
DROP TABLE ranges;
2021-03-10