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" /> <asp:boundfield datafield="au_fname" headertext="au_fname" sortexpression="au_fname" /> <asp:boundfield datafield="state" headertext="state" sortexpression="state" /> </columns> </asp:gridview> <asp:sqldatasource connectionstring="<%$ connectionstrings:pubs %>" id="sqldatasource1" runat="server" selectcommand="select au_id, au_lname, au_fname, state from authors where state = isnull(@state, state)" cancelselectonnullparameter="false"> <selectparameters> <asp:controlparameter controlid="dropdownlist1" name="state" propertyname="selectedvalue" type="string" /> </selectparameters> </asp:sqldatasource> </div> </form></body></html>
新聞熱點
疑難解答