Latest web development tutorials

funzione SQL ISNULL (), NVL (), IFNULL () e COALESCE ()

funzione SQL ISNULL (), NVL (), IFNULL () e COALESCE ()

Guardate la seguente tabella "Prodotti":

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder
1 Jarlsberg 10.45 16 15
2 Mascarpone 32.56 23
3 Gorgonzola 15.67 9 20

Se "UnitsOnOrder" è opzionale, e può contenere valori NULL.

Usiamo la seguente istruzione SELECT:

SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products

Nell'esempio precedente, se c'è "UnitsOnOrder" valore è NULL, allora il risultato è NULL.

la funzione di Microsoft ISNULL () viene utilizzato per specificare come gestire i valori NULL.

NVL (), IFNULL () e COALESCE function () può anche ottenere gli stessi risultati.

Qui, speriamo valore NULL è 0.

Ora, se "UnitsOnOrder" è NULL, esso non influisce sul calcolo, perché se il valore è NULL, ISNULL () restituisce 0:

SQL Server / MS Access

SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))
FROM Products

oracolo

Oracle non ha IsNull () function. Tuttavia, possiamo usare la funzione NVL () per ottenere lo stesso risultato:

SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products

MySQL

MySQL ha anche funzione simile ISNULL (). Ma funziona con ISNULL di Microsoft () è un po 'diverso.

In MySQL, si può utilizzare la funzione IFNULL () come segue:

SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products

Oppure possiamo usare la funzione COALESCE () come segue:

SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products