表tab_a
ID, --, 比较列
'1','xx',700
'2','xx',600
'3','xx',800表tab_b
id,Tab_aID,求和列
1, '1', 200
2, '1', 300
3, '3', 200
4, '3', 500
5, '1', 100想实现
select * from tab_a where 比较列> (select SUM(求和列) from tab_b where Tab_aID =tab_a.ID)但是由于有的时候 select SUM(求和列) from tab_b where Tab_aID =tab_a.ID 为NULL
比如当tab_a的ID=2时
这时这一行就没法筛选出来于是我想写个函数完成
CREATE FUNCTION getCount(@ID AS varchar(50))
RETURNS varchar(6) 
AS
BEGIN 
RETURN LEFT((SELECT SUM(HCount) FROM PD_JobJYJL WHERE JID LIKE @JIDStr), 6)
END
结果还是一样,有时函数就返回NULL
请问我如何在函数中判断是否为空,
当空时这个函数返回0我在调用就不会有问题了

解决方案 »

  1.   

    select * from tab_a where 比较列> isnull((select SUM(求和列) from tab_b where Tab_aID =tab_a.ID),0)
    仅是为了比较这样试试
      

  2.   


    select * from tab_a 
    where 比较列> (select isnull(SUM(求和列),0) from tab_b where Tab_aID =tab_a.ID) 
      

  3.   

    --应该不用另外写函数,直接用IsNull函数即可实现你的要求,具体如下:--创建测试环境
    Create table tab_a(id int,descp varchar(20),比较列 int)
    go
    Create table tab_b(id int,Tab_aID int,求和列 int)
    go
    insert tab_a
    select '1','xx',700 union all select 
    '2','xx',600  union all select 
    '3','xx',800  insert tab_b
    select 1, '1', 200  union all select 
    2, '1', 300  union all select 
    3, '3', 200  union all select 
    4, '3', 500 union all select 
    5, '1', 100 --查询
    select * from tab_a a
    where exists(
    select id from (select  a.id from tab_a a
    left join tab_b b on a.id=b.Tab_aID 
    group by a.id
    having sum(isnull(a.比较列,0))>sum(isnull(b.求和列,0))) c where id=a.id)/*
    结果
    id          descp                比较列
    ----------- -------------------- -----------
    1           xx                   700
    2           xx                   600
    3           xx                   800(3 row(s) affected)
    */--删除测试环境
    truncate table tab_a
    truncate table tab_b
    drop table tab_a,tab_b
      

  4.   

    为空的换转换一下即可,不必用函数.select a.* from tab_a a where 比较列 > isnull((select sum(求和列) from tab_b where b.tab_aid = a.id),0)