SQL NULL- funksies
SQL IFNULL(), ISNULL(), COALESCE() en NVL() Funksies
Kyk na die volgende "Produkte"-tabel:
P_Id | ProductName | UnitPrice | UnitsInStock | UnitsOnOrder |
---|---|---|---|---|
1 | Jarlsberg | 10.45 | 16 | 15 |
2 | Mascarpone | 32.56 | 23 | |
3 | Gorgonzola | 15.67 | 9 | 20 |
Gestel die "UnitsOnOrder"-kolom is opsioneel en kan NULL-waardes bevat.
Kyk na die volgende SELECT-stelling:
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)
FROM Products;
In die voorbeeld hierbo, as enige van die "UnitsOnOrder" waardes NULL is, sal die resultaat NULL wees.
Oplossings
MySQL
Die MySQL IFNULL()
-funksie laat jou 'n alternatiewe waarde terugstuur as 'n uitdrukking NULL is:
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))
FROM Products;
of ons kan die funksie soos volg gebruik:
COALESCE()
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;
SQL Server
Die SQL Server-
ISNULL()
funksie laat jou 'n alternatiewe waarde terugstuur wanneer 'n uitdrukking NULL is:
SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))
FROM Products;
MS Access
Die MS Access-
IsNull()
funksie gee TRUE (-1) terug as die uitdrukking 'n nulwaarde is, anders ONWAAR (0):
SELECT ProductName, UnitPrice * (UnitsInStock + IIF(IsNull(UnitsOnOrder), 0, UnitsOnOrder))
FROM Products;
Orakel
Die Oracle- NVL()
funksie bereik dieselfde resultaat:
SELECT ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder, 0))
FROM Products;