在 DB2 查询中使用局部变量?
Use Local Variables with a DB2 Query?
我正在尝试编写一个使用局部变量的 DB2 查询。我真的只是想让查询更容易维护 运行.
这是基本查询:
WITH MYTAB (CustomerId, VisitID, Sale, DateTime)
AS
(
VALUES
(1, 1, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
,
(1, 3, 'N', '2021-04-23 21:16:00'::TIMESTAMP)
,
(2, 2, 'N', '2021-04-24 20:16:00'::TIMESTAMP)
,
(2, 4, 'Y', '2021-04-25 20:16:00'::TIMESTAMP)
,
(2, 6, 'N', '2021-04-25 23:16:00'::TIMESTAMP)
,
(3, 5, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
, (
3, 7, 'N', '2021-05-23 20:16:00'::TIMESTAMP)
)
SELECT *
FROM MYTAB A
WHERE DateTime > '2021-04-24'
如何使用变量来编写同样的语句?以下不会运行但给出思路:
WITH MYTAB (CustomerId, VisitID, Sale, DateTime)
AS
(
VALUES
(1, 1, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
,
(1, 3, 'N', '2021-04-23 21:16:00'::TIMESTAMP)
,
(2, 2, 'N', '2021-04-24 20:16:00'::TIMESTAMP)
,
(2, 4, 'Y', '2021-04-25 20:16:00'::TIMESTAMP)
,
(2, 6, 'N', '2021-04-25 23:16:00'::TIMESTAMP)
,
(3, 5, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
,
(3, 7, 'N', '2021-05-23 20:16:00'::TIMESTAMP)
)
WITH VAR_START(STARTDTTM) AS (VALUES(DATE('2021-01-01')))
SELECT *
FROM MYTAB A,VAR_START
WHERE DateTime > STARTDTTM
不确定这是否是您要问的,但您可以在一个查询中包含多个 CTE:
WITH MYTAB (CustomerId, VisitID, Sale, DateTime) AS
(
VALUES
(1, 1, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
, (1, 3, 'N', '2021-04-23 21:16:00'::TIMESTAMP)
, (2, 2, 'N', '2021-04-24 20:16:00'::TIMESTAMP)
) , VAR_START(STARTDTTM) AS (
VALUES (DATE('2021-01-01') )
)
SELECT *
FROM MYTAB A, VAR_START
WHERE DateTime > STARTDTTM
如果要使用变量,可以使用匿名块或存储过程。另一种选择是使用 returns 和 table 并将参数作为参数的函数。
我正在尝试编写一个使用局部变量的 DB2 查询。我真的只是想让查询更容易维护 运行.
这是基本查询:
WITH MYTAB (CustomerId, VisitID, Sale, DateTime)
AS
(
VALUES
(1, 1, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
,
(1, 3, 'N', '2021-04-23 21:16:00'::TIMESTAMP)
,
(2, 2, 'N', '2021-04-24 20:16:00'::TIMESTAMP)
,
(2, 4, 'Y', '2021-04-25 20:16:00'::TIMESTAMP)
,
(2, 6, 'N', '2021-04-25 23:16:00'::TIMESTAMP)
,
(3, 5, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
, (
3, 7, 'N', '2021-05-23 20:16:00'::TIMESTAMP)
)
SELECT *
FROM MYTAB A
WHERE DateTime > '2021-04-24'
如何使用变量来编写同样的语句?以下不会运行但给出思路:
WITH MYTAB (CustomerId, VisitID, Sale, DateTime)
AS
(
VALUES
(1, 1, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
,
(1, 3, 'N', '2021-04-23 21:16:00'::TIMESTAMP)
,
(2, 2, 'N', '2021-04-24 20:16:00'::TIMESTAMP)
,
(2, 4, 'Y', '2021-04-25 20:16:00'::TIMESTAMP)
,
(2, 6, 'N', '2021-04-25 23:16:00'::TIMESTAMP)
,
(3, 5, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
,
(3, 7, 'N', '2021-05-23 20:16:00'::TIMESTAMP)
)
WITH VAR_START(STARTDTTM) AS (VALUES(DATE('2021-01-01')))
SELECT *
FROM MYTAB A,VAR_START
WHERE DateTime > STARTDTTM
不确定这是否是您要问的,但您可以在一个查询中包含多个 CTE:
WITH MYTAB (CustomerId, VisitID, Sale, DateTime) AS
(
VALUES
(1, 1, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
, (1, 3, 'N', '2021-04-23 21:16:00'::TIMESTAMP)
, (2, 2, 'N', '2021-04-24 20:16:00'::TIMESTAMP)
) , VAR_START(STARTDTTM) AS (
VALUES (DATE('2021-01-01') )
)
SELECT *
FROM MYTAB A, VAR_START
WHERE DateTime > STARTDTTM
如果要使用变量,可以使用匿名块或存储过程。另一种选择是使用 returns 和 table 并将参数作为参数的函数。