读书人

isnull惹出来的麻烦.居然和left join打

发布时间: 2012-04-02 19:58:59 作者: rapoo

isnull惹出来的麻烦.....居然和left join打架...呜~
还是使用很俗套的例子表举例~

学生成绩表和班级信息表
CREATE TABLE [dbo].[T_Class] (
[classid] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
[classname] [varchar] (50) NULL
) ON [PRIMARY]
GO

/*********************/

CREATE TABLE [dbo].[T_student] (
[sid] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
[sname] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[class] [int] NULL ,
[score] [int] NULL
) ON [PRIMARY]
GO
/*---------------------*/
class的数据
classid classname
1A
2B
3C
/*---------------------*/
student的数据
sid sname class score
1aa11NULL
2aa2290
3bb1270
4aa3180
/******************************/
select classname, score from t_class C
left join t_student S on C.classid = S.class
执行结果
ANULL
A80
B90
B70
CNULL

可是……
加上isnull就不对了哇~
select classname, isnull(0, score) as score from t_class C
left join t_student S on C.classid = S.class

A0
A0
B0
B0
C0

====================
怎么解决呢?不太了解原因,晕了~

[解决办法]
isnull用错了,写反位置:

select classname, isnull(score,0) as score from t_class C
left join t_student S on C.classid = S.class
[解决办法]
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。

读书人网 >SQL Server

热点推荐