日期:2014-05-19  浏览次数:20403 次

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
1 A
2 B
3 C
/*---------------------*/
student的数据
              sid                 sname         class         score
1 aa1 1 NULL
2 aa2 2 90
3 bb1 2 70
4 aa3 1 80
/******************************/
select   classname,   score   from   t_class   C  
    left   join   t_student   S   on   C.classid   =   S.class
执行结果
A NULL
A 80
B 90
B 70
C NULL

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

A 0
A 0
B 0
B 0
C 0

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

------解决方案--------------------
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。