Use the value of a string variable in SQL FOR-IN (SELECT) loop

雨燕双飞 提交于 2019-12-23 03:39:26

问题


I have an SQL procedure, that should execute a FOR-IN (SELECT ..) loop, where the SELECT content should vary depending on some input parameters. My idea was to store the SELECT string into a variable, and then try to extract the variable value in the FOR-IN loop but without success so far (earlier there was a fix SELECT statement used there, that's what I am trying to replace now). The code looks about as follows

PROCEDURE run(p_boolean BOOLEAN)
IS
BEGIN
  DECLARE
    v_mystring VARCHAR(50);
  BEGIN
    IF p_boolean = TRUE
    THEN
      v_mystring := 'SELECT something...';
    ELSE
      v_mystring := 'SELECT something else...';
    END IF;

    FOR p_table_name IN (would-like-to-use-the-value-of-v_mystring-here-some-way)
    LOOP
      ...
    END LOOP;

  END;
END;

Being quite novice in SQL, it might well happen that the entire concept of trying to use a string variable value here is wrong. I browsed through some tutorials and tried some other ideas (e.g. cursor), but no result. Any idea is appreciated


回答1:


Assuming Oracle's PL/SQL ,You can open a REFCURSOR using dynamic String and call it in a LOOP..

PROCEDURE run(p_boolean BOOLEAN)
IS
BEGIN
  DECLARE
    v_mystring VARCHAR(50);
    v_my_ref_cursor sys_refcursor;
  BEGIN
    IF p_boolean = TRUE
    THEN
      v_mystring := 'SELECT something...';
    ELSE
      v_mystring := 'SELECT something else...';
    END IF;

    OPEN v_my_ref_cursor FOR v_mystring;

    LOOP
      FETCH v_my_ref_cursor INTO your_variables/record
      EXIT WHEN v_my_ref_cursor%NOTFOUND;
        ..

    END LOOP;
    CLOSE v_my_ref_cursor;

  END;
END;


来源:https://stackoverflow.com/questions/21631941/use-the-value-of-a-string-variable-in-sql-for-in-select-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!