tax_id in acc_trans
[kivitendo-erp.git] / sql / Pg-upgrade2 / add_tax_id_to_acc_trans.sql
1 -- @tag: add_tax_id_to_acc_trans
2 -- @description: Neue Spalte tax_id in der acc_trans
3 -- @depends: release_2_7_0 
4
5   --Neue Spalte tax_id in acc_trans:
6   ALTER TABLE acc_trans ADD tax_id integer;
7
8   --Spalte mit Werten füllen:
9   UPDATE acc_trans ac SET tax_id=
10                 (select tk.tax_id from taxkeys tk 
11                       where tk.taxkey_id=ac.taxkey 
12                       AND tk.startdate <= COALESCE(
13                             (select ar.deliverydate from ar where ar.id=ac.trans_id), 
14                             (select ar.transdate from ar where ar.id=ac.trans_id), 
15                             (select ap.transdate from ap where ap.id=ac.trans_id), 
16                             (select gl.transdate from gl where gl.id=ac.trans_id), 
17                             ac.transdate )
18                       order by startdate desc limit 1);
19
20   --Spalten, die noch null sind (nur bei Einträgen möglich, wo auch taxkey null ist)
21   UPDATE acc_trans SET tax_id= (SELECT id FROM tax WHERE taxkey=0 LIMIT 1) where tax_id is null;
22  
23   --tax_id als Pflichtfeld definieren:
24   ALTER TABLE acc_trans ALTER tax_id SET NOT NULL;
25