1 -- @tag: add_tax_id_to_acc_trans
 
   2 -- @description: Neue Spalte tax_id in der acc_trans
 
   3 -- @depends: release_3_0_0 charts_without_taxkey
 
   5   --Neue Spalte tax_id in acc_trans:
 
   6   ALTER TABLE acc_trans ADD tax_id integer;
 
   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), 
 
  18                       ORDER BY startdate DESC LIMIT 1);
 
  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;
 
  23   --tax_id als Pflichtfeld definieren:
 
  24   ALTER TABLE acc_trans ALTER tax_id SET NOT NULL;