日期:2013-05-09  浏览次数:20514 次

ISNULL
使用指定的替换值替换 NULL。

语法
ISNULL ( check_expression , replacement_value )

参数
check_expression

将被检查能否为 NULL的表达式。check_expression 可以是任何类型的。

replacement_value

在 check_expression 为 NULL时将前往的表达式。replacement_value 必须与 check_expresssion 具有相反的类型。

前往类型
前往与 check_expression 相反的类型。

注释
如果 check_expression 不为 NULL,那么前往该表达式的值;否则前往 replacement_value。

示例
A. 将 ISNULL 与 AVG 一同使用
下面的示例查找所有书的平均价格,用值 $10.00 替换 titles 表的 price 列中的所有 NULL 条目。

USE pubs
GO
SELECT AVG(ISNULL(price, $10.00))
FROM titles
GO

下面是结果集:

--------------------------
14.24                     

(1 row(s) affected)

B. 使用 ISNULL
下面的示例为 titles 表中的所有书选择书名、类型及价格。如果一个书名的价格是 NULL,那么在结果集中显示的价格为 0.00。

USE pubs
GO
SELECT SUBSTRING(title, 1, 15) AS Title, type AS Type,
   ISNULL(price, 0.00) AS Price
FROM titles
GO

C. 在Full Join情况下使用ISNULL
表A:
tid
uid
anum

表B:
tbid
uid
bnum1
bnum2
需求通过uid全连接两个表:
select a.tid,a.uid,a.anum,b.bnum1,b.bnum2 from a full join b on a.uid=b.uid
全连接会有很多为空的情况,可以使用ISNull来处理,改为:
select isnull(a.tid,b.tid),isnull(a.uid,b.uid),isnull(a.anum,0),isnull(b.bnum1,0),isnull(b.bnum2,0) from a full join b on a.uid=b.uid

再加上一种在asp.net2.0中的综合用法:

<%@ Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>Showing all items in a filtered list</title></head><body>    <form id="form1" runat="server">    <div>        <asp:DropDownList AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlDataSource2"            DataTextField="state" DataValueField="state" ID="DropDownList1" runat="server">            <asp:ListItem Value="">ALL</asp:ListItem>        </asp:DropDownList><asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:Pubs %>"            ID="SqlDataSource2" runat="server" SelectCommand="SELECT DISTINCT [state] FROM [authors]">        </asp:SqlDataSource>        <br />        <br />        <asp:GridView AutoGenerateColumns="False" DataSourceID="SqlDataSource1"            ID="GridView1" runat="server" DataKeyNames="au_id">            <Columns>              <asp:BoundField DataField="au_id" HeaderText="au_id" ReadOnly="True" SortExpression="au_id" />              <asp:BoundField DataField="au_lname" HeaderText="au_lname" SortExpression="au_lname" />       &n