2016-08-12 73 views
-3

我需要刪除特定架構中每個表中的每個數據,以使條件處於非活動狀態。活動/非活動值是一個布爾值,每個表都有這個列。刪除每個非活動數據SQL

我該怎麼做?

+1

您正在尋求一種解決方案,而無需顯示自己的努力甚至是有關您的模式的信息。 – Nicarus

+0

這個問題對我來說聽起來很完美。我看不出爲什麼這麼多票。 – Christian

回答

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();您想「清理」您的表格!

1

你不能只是神奇地做到這一點,你需要編寫一個查詢來創建您的查詢。

事情是這樣的:

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

會給你的表的名單,然後只需添加到一個查詢,說

delete from <tablename> where active = 0