Latest web development tutorials

fonction SQL ISNULL (), NVL (), IFNULL () et COALESCE ()

fonction SQL ISNULL (), NVL (), IFNULL () et COALESCE ()

Regardez le "Produits" tableau suivant:

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

Si "Unités commandées" est facultative, et peut contenir des valeurs NULL.

Nous utilisons l'instruction SELECT suivante:

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

Dans l'exemple ci-dessus, s'il y a une valeur "Unités commandées" est NULL, alors le résultat est NULL.

ISNULL () la fonction de Microsoft est utilisé pour spécifier comment gérer les valeurs NULL.

fonction NVL (), IFNULL () et COALESCE () peut également obtenir les mêmes résultats.

Ici, nous espérons valeur NULL est 0.

Maintenant, si "Unités commandées" est NULL, il ne sera pas affecter le calcul, parce que si la valeur est NULL, ISNULL () retourne 0:

SQL Server / MS Access

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

oracle

Oracle n'a pas isNull function (). Cependant, nous pouvons utiliser la fonction NVL () pour obtenir le même résultat:

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

MySQL

MySQL a également une fonction similaire ISNULL (). Mais il fonctionne avec ISNULL de Microsoft () est un peu différent.

En MySQL, nous pouvons utiliser IFNULL () comme suit:

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

Ou nous pouvons utiliser la fonction COALESCE () comme suit:

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