Sample Header Ad - 728x90

How to obtain the result of a dynamic query without a cursor in an SP?

0 votes
1 answer
60 views
I tried creating a procedure to adjust a sequence according to the max value in a column. To get the max value from the column and store it in a variable I ended up using a "dummy" cursor. I assume there is a simpler way, but I could not get any of them to work. Any suggestions on how to get rid of the cursor and still be able to use the max value in the alter statement? --#SET TERMINATOR @ CREATE OR REPLACE PROCEDURE Adjust_Sequence( IN p_table_schema VARCHAR(128), IN p_table_name VARCHAR(128), IN p_column_name VARCHAR(128), IN p_sequence_name VARCHAR(128) ) LANGUAGE SQL BEGIN DECLARE v_max_value BIGINT DEFAULT 1; DECLARE v_sql_stmt VARCHAR(1000); DECLARE cur CURSOR FOR S; -- Construct SQL to get the max value of the specified column SET v_sql_stmt = 'SELECT COALESCE(MAX(' || p_column_name || '), 0) + 1 FROM ' || p_table_schema || '.' || p_table_name; -- Prepare and execute the statement properly PREPARE S FROM v_sql_stmt; OPEN cur; FETCH cur INTO v_max_value; CLOSE cur; -- Construct SQL to alter the sequence to restart with the new max value SET v_sql_stmt = 'ALTER SEQUENCE ' || p_sequence_name || ' RESTART WITH ' || v_max_value; -- Execute the sequence alteration EXECUTE IMMEDIATE v_sql_stmt; END @ --#SET TERMINATOR ;
Asked by Lennart - Slava Ukraini (23862 rep)
Feb 20, 2025, 02:56 PM
Last activity: Feb 20, 2025, 07:42 PM