表1
La    Le    Lc
a     Y     1
b     Y     2
c     Z     3
表2
Lcx    Le    Lf
4      Y      7
2      X      6
3      Z      8表1.Le=表2.Le 
想写个函数: 查询表1 La字段的c是否存在,若不存在,则返回-1 
  若存在,则判断它的Lc 是否大于表2的Lcx,若大于则返回2 若小于则返回-2
 这个函数怎么写吖。

解决方案 »

  1.   


    create function dbo.fn_air()
    returns int
    as
    begin
     declare @x int
     
     if not exists(select 1 from 表1 where La='c')
     begin
      select @x=-1
      return @x
     end
     
     if exists(select 1 
               from 表1 a
               inner join 表2 b on a.Le=b.Le
               where a.La='c' and a.Lc>b.Lcx)
     begin
       select @x=2
     end
     else
     begin
       select @x=-2
     end
     
     return @x
    end
      

  2.   


    create function retValue()
    returns int  AS 
    begin 
    declare @cnt int 
    declare @ret int 
    select @cnt = count(*) from 表1 where la = 'c'

    if @cnt = 0 
      select @ret = -1
    else
      select @ret = (case when lc > lcx  then 2 else -2 end) from 表1 a inner join 表2 b on 表1.Le = 表2.Le where la = 'c'
            return @ret
    end
      

  3.   

    alter function dbo.fn_air()
    returns int
     as
    begin
    declare @x int 
    declare @s int
     if exists(select 1 from a where La='c')
     begin
      select @x=Lc from a where La='c'
      select @s=Lcx from b
    if(@x>@s)
    begin
    select @x=2
    end
    else
    begin
    select @x=-2
    end
     end
    else
    begin
    select @x=-1
    end
     return  @x 
    end