Stored Procedure

0

I have lookup table that contains databasename and tablename with indicators. I want to loop through each table first to check for duplicates and if found will have to do some clean up.

Can someone help me with the sP?

CREATE OR REPLACE PROCEDURE record_example() LANGUAGE plpgsql AS $$ DECLARE rec RECORD; BEGIN FOR rec IN select db_nm,tbl_nm from Tbl_Lookup where dupcheck_ind <> 'Y' LOOP DML1; DML2; DML3; END LOOP; END; $$;

Thanks KN

KN
질문됨 일 년 전188회 조회
1개 답변
4
수락된 답변

Here's an example

CREATE OR REPLACE PROCEDURE record_example()
LANGUAGE plpgsql
AS $$
DECLARE
    rec RECORD;
BEGIN
    FOR rec IN SELECT db_nm, tbl_nm FROM Tbl_Lookup WHERE dupcheck_ind <> 'Y'
    LOOP
        -- Check for duplicates in the table
        IF EXISTS (SELECT 1
                   FROM (SELECT COUNT(*)
                         FROM rec.db_nm || '.' || rec.tbl_nm
                         GROUP BY your_unique_key_columns
                         HAVING COUNT(*) > 1) AS duplicates)
        THEN
            -- DML1: Perform clean-up task 1, e.g., delete duplicates
            EXECUTE format('DELETE FROM %I.%I WHERE ...;', rec.db_nm, rec.tbl_nm);

            -- DML2: Perform clean-up task 2
            EXECUTE format('UPDATE %I.%I SET ...;', rec.db_nm, rec.tbl_nm);

            -- DML3: Perform clean-up task 3
            EXECUTE format('INSERT INTO %I.%I (...) VALUES (...);', rec.db_nm, rec.tbl_nm);
        END IF;
    END LOOP;
END;
$$;

replace your_unique_key_columns with the appropriate column names used to identify duplicates Customize the DML1, DML2, and DML3 statements as needed for your specific clean-up tasks.

This stored procedure uses dynamic SQL with EXECUTE format() to perform the clean-up tasks on the tables specified in the lookup table. The IF EXISTS statement checks for duplicates based on the specified unique key columns. If duplicates are found, the procedure executes the clean-up tasks (DML1, DML2, and DML3) for that table.

profile picture
전문가
답변함 일 년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠