存储过程:FOR 中的 IF 语句...在

Stored procedures: IF statement within FOR...IN

提问人:tamboo 提问时间:4/15/2023 最后编辑:marc_stamboo 更新时间:4/15/2023 访问量:189

问:

我的存储过程有一个循环,但我想在循环中包含一个语句,如果该语句为 true,则只循环一行 - 否则,循环所有 3 行。FORIFIF

示例如下:

  FOR snippets IN (
    if digit = 'only one' then
        select
          "one" as number
    else
        select
          "one" as number
        union all
        select
          "two" as number
        union all 
        select
          "three" as number
    end if;)
SQL for 循环 if 语句 存储过程 google-bigquery

评论


答:

0赞 markalex 4/15/2023 #1

您可以通过两种主要方式执行此操作:

  1. 筛选提供的数据,以便进行迭代。像这样的东西:
FOR snippets IN (
        select "one" as number
        union all
        select "two" as number
        where digit = 'only one'
        union all 
        select "three" as number
        where digit = 'only one')
  1. 在 for 内部添加检查,这将在需要时中断循环:
FOR snippets IN (
      select "one" as number
      union all
      select "two" as number
      union all 
      select "three" as number)
DO
    if digit = 'only one' and snippets <> 'one' then
        BREAK;
    end if;
END FOR;

评论

0赞 tamboo 4/18/2023
我可以在循环中添加一个情况,如果变量为 true,它只遍历其中一个 select 语句,如果变量为 false,它会遍历所有 3 个 select 语句?我已经尝试过了,但没有运气。
0赞 markalex 4/18/2023
@tamboo,你的意思就像我的第二个片段一样吗?if my_boolean_var and snippets <> 'one'
0赞 Jaytiger 4/15/2023 #2

您可以使用如下所示的临时表的解决方法。

DECLARE digit DEFAULT 'only one';

IF digit = 'only one' THEN
  CREATE TEMP TABLE snippets AS
    SELECT 'one' number;
ELSE
  CREATE TEMP TABLE snippets AS
    SELECT 'one' number UNION ALL
    SELECT 'two' number UNION ALL
    SELECT 'three' number;
END IF;

FOR snippet IN (SELECT * FROM snippets)
DO
  SELECT snippet.number;
END FOR;

-- script result
+--------+
| number |
+--------+
| one    |
+--------+

评论

0赞 tamboo 4/18/2023
感谢您的帮助。我注意到当我将数字声明为另一个值时,它不会产生所有三个输入......
0赞 Jaytiger 4/18/2023
如果设置为其他值,它将返回一行的查询结果 3 次。digitonly one