uTools-Manuals/docs/sql/NULL 函数.html
2019-05-07 10:15:08 +08:00

15 lines
2.5 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<div class="m-bg">
<h1>SQL NULL 函数</h1>
<h2>SQL ISNULL()、NVL()、IFNULL() 和 COALESCE() 函数</h2> <p>请看下面的 "Products" 表:</p> <table class="reference notranslate">
<tr>
<th align="left">P_Id</th> <th align="left">ProductName</th> <th align="left">UnitPrice</th> <th align="left">UnitsInStock</th> <th align="left">UnitsOnOrder</th> </tr>
<tr>
<td>1</td> <td>Jarlsberg</td> <td>10.45</td> <td>16</td> <td>15</td> </tr>
<tr>
<td>2</td> <td>Mascarpone</td> <td>32.56</td> <td>23</td> <td> </td> </tr>
<tr>
<td>3</td> <td>Gorgonzola</td> <td>15.67</td> <td>9</td> <td>20</td> </tr>
</table>
<p>假如 "UnitsOnOrder" 是可选的,而且可以包含 NULL 值。</p> <p>我们使用下面的 SELECT 语句:</p> <div class="code notranslate"><pre><code class="language-sql"><div> SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)<br/> FROM Products</div></code></pre></div> <p>在上面的实例中,如果有 "UnitsOnOrder" 值是 NULL那么结果是 NULL。</p> <p>微软的 ISNULL() 函数用于规定如何处理 NULL 值。</p> <p>NVL()、IFNULL() 和 COALESCE() 函数也可以达到相同的结果。</p> <p>在这里,我们希望 NULL 值为 0。</p> <p>下面,如果 "UnitsOnOrder" 是 NULL则不会影响计算因为如果值是 NULL 则 ISNULL() 返回 0</p> <p><b>SQL Server / MS Access</b></p> <div class="code notranslate"><pre><code class="language-sql"><div> SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))<br/> FROM Products</div></code></pre></div> <p><b>Oracle</b></p> <p>Oracle 没有 ISNULL() 函数。不过,我们可以使用 NVL() 函数达到相同的结果:</p> <div class="code notranslate"><pre><code class="language-sql"><div> SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))<br/> FROM Products</div></code></pre></div> <p><b>MySQL</b></p> <p>MySQL 也拥有类似 ISNULL() 的函数。不过它的工作方式与微软的 ISNULL() 函数有点不同。</p> <p>在 MySQL 中,我们可以使用 IFNULL() 函数,如下所示:</p> <div class="code notranslate"><pre><code class="language-sql"><div> SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))<br/> FROM Products</div></code></pre></div> <p>或者我们可以使用 COALESCE() 函数,如下所示:</p> <div class="code notranslate"><pre><code class="language-sql"><div> SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))<br/> FROM Products</div></code></pre></div> <br/><div class="text-center padding-10 margin-t-5">
</div>
</div>