删除每个非活动数据SQL

时间:2016-08-12 17:16:34

标签: sql postgresql

我需要删除特定架构中每个表中满足条件的非活动状态的每个数据。活动/非活动值是一个布尔值,每个表都有此列。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

你不能只是神奇地做到这一点,你需要编写一个查询来创建你的查询。

这样的事情:

select distinct tablename from information_schema.columns where columnname = 'Active'

会给你一个表列表,然后将其添加到一个说

的查询中
delete from <tablename> where active = 0

答案 1 :(得分:0)

您可以创建一个功能来执行此操作:

CREATE OR REPLACE FUNCTION delete_inactive_records()
RETURNS TEXT AS
$BODY$
DECLARE VTABLES     RECORD; 
    VRESULT     TEXT;
    VNUM_ROWS   INTEGER;
BEGIN
    VRESULT = '';
    FOR VTABLES IN  (
            select distinct table_schema || '.' || table_name as table_name
            from   information_schema.tables t 
            where   exists  (
                    select  1 
                    from    information_schema.columns c 
                    where   c.table_catalog = t.table_catalog 
                    and     c.table_schema = c.table_schema 
                    and     c.table_name = t.table_name 
                    and     c.column_name = 'active'
                    and     t.table_catalog in ("<your_table_catalog1>", "<your_table_catalog2>", "<etc>")
                    )
            order   by 1
            )
    LOOP
        RAISE NOTICE 'DELETING FROM %...', VTABLES.TABLE_NAME;
        EXECUTE ('DELETE FROM ' || VTABLES.TABLE_NAME || ' WHERE active = 0');
        get diagnostics vNUM_ROWS = ROW_COUNT;
        VRESULT = VRESULT || vNUM_ROWS || ' records were deleted from ' || VTABLES.TABLE_NAME || chr(13);       
    END LOOP;
    return VRESULT;
end;
$BODY$
  LANGUAGE plpgsql VOLATILE;

然后在任何时候打电话给select delete_inactive_records();&#34;清理&#34;你的桌子!