在 while 循环中访问临时表

Posted

技术标签:

【中文标题】在 while 循环中访问临时表【英文标题】:Access a temp table in a while loop 【发布时间】:2021-10-24 06:11:22 【问题描述】:

我正在创建一个临时表,然后尝试像这样循环该表:

CREATE TEMP TABLE `table_name` AS 
    SELECT 1 AS row, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 1 WEEK) AS start, DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)) AS end_date_plus_one UNION ALL
    SELECT 2, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 2 WEEK), DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 1 WEEK) UNION ALL
    SELECT 3, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 3 WEEK), DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 2 WEEK) UNION ALL
    SELECT 4, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 4 WEEK), DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 3 WEEK)
    ;

BEGIN
    DECLARE loopRow INT64;
    SET loopRow = 1;

    WHILE table_name.start IS NOT NULL DO
        SELECT start FROM `table_name` WHERE row = loopRow;
        SET loopRow = loopRow + 1;
    END WHILE;
END 

预期的输出是开始日期列表,当没有更多日期时会中断循环。我收到错误Unrecognized name: table_name

【问题讨论】:

【参考方案1】:

试试看是否有帮助。


create temp table table_name AS     SELECT 1 AS row, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 1 WEEK) AS start, DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)) AS end_date_plus_one UNION ALL
    SELECT 2, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 2 WEEK), DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 1 WEEK) UNION ALL
    SELECT 3, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 3 WEEK), DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 2 WEEK) UNION ALL
    SELECT 4, DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 4 WEEK), DATE_SUB(DATE_TRUNC(CURRENT_DATE('Europe/London'), WEEK(MONDAY)), INTERVAL 3 WEEK)
    ;
BEGIN
    DECLARE loopRow INT64;
    SET loopRow = (SELECT COUNT(START) FROM table_name);
    WHILE loopRow >= 1  DO
        SELECT start FROM table_name WHERE row = loopRow;
        SET loopRow = loopRow - 1;
    END WHILE;
END

【讨论】:

以上是关于在 while 循环中访问临时表的主要内容,如果未能解决你的问题,请参考以下文章

SQL 中将游标循环查询的结果插入到临时表中

如何创建临时表或仅从循环中的列中选择不同的值

MySQL 临时表插入

sqlserver 表循环-游标表变量临时表

SQL用循环查询的结果 建临时表

MySQL存储过程循环遍历变量并插入临时表