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
質問済み 1年前187ビュー
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
エキスパート
回答済み 1年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ