日期:2014-05-18  浏览次数:20447 次

关于sql中case判断的使用
SQL code


create function SXTEST(@type int,@first float,@second float)
returns float
as
begin
declare @result float
if(@type=1)--"+"
begin
    set @result=@first+@second
end
if(@type=2)--"-"
begin
    set @result=@first-@second
end
return @result
end





以上代码不用if,用case when 如何实现??

------解决方案--------------------
SQL code
create function SXTEST(@type int,@first float,@second float)
returns float
as
begin
declare @result float
select @result = case @type when 1 then @first+@second when 2 then @first - @second end
end

------解决方案--------------------
SQL code

create function SXTEST(@type int,@first float,@second float)
returns float
as
begin
declare @result float
SELECT @result= CASE WHEN @type=1 THEN @first+@second 
                     WHEN @type=0 THEN @first-@second
                     ELSE 0 END
return @result
end