PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Come convertire una stringa vuota in null in PostgreSQL?

Esiste la funzione NULLIF():

SELECT NULLIF(var, '');

Se var contiene il valore di $2, otterrai NULL al suo posto.
Nell'esempio sostituisco la stringa vuota '' con NULL.

Non esiste una stringa vuota per il tipo integer. Semplicemente non è possibile. Poiché NULLIF() non può cambiare il tipo di dato, devi sanificare l'input in PHP.

Se non hai definito un valore predefinito per la colonna, puoi anche omettere semplicemente la colonna nel comando INSERT e verrà riempita con NULL (che è il DEFAULT predefinito).

Verifica in PHP se il parametro è vuoto e, in tal caso, non includere la colonna nel comando INSERT.

Oppure usa il letterale NULL di PHP, come mostra Quassnoi qui.

Il resto ha senso solo per i tipi stringa

Per essere assolutamente certi che nessuno possa inserire una stringa vuota, aggiungi un vincolo CHECK alla tabella:

ALTER TABLE tr_view ADD CONSTRAINT tr_view_age_not_empty CHECK (age <> '');

Per evitare eccezioni causate da questo, potresti aggiungere un trigger che corregga automaticamente l'input:

CREATE OR REPLACE FUNCTION trg_tr_view_avoid_empty()
  RETURNS trigger AS $func$
BEGIN
  IF NEW.age = '' THEN
    NEW.age := NULL;
  END IF;
  IF NEW.month = '' THEN
    NEW.month := NULL;
  END IF;
  RETURN NEW;
END
$func$ LANGUAGE plpgsql;

CREATE TRIGGER tr_view_avoid_empty
BEFORE INSERT OR UPDATE ON tr_view
FOR EACH ROW
WHEN (NEW.age = '' OR NEW.month = '')
EXECUTE PROCEDURE trg_tr_view_avoid_empty();