您的位置:首页 > 数据库

[MSSQL] 如何自己定义函数(返回多变量)

2008-10-08 19:20 260 查看
前些天在写存储过程的时候,需要用到这样一个功能:

14.2返回15 0.8

14.0返回14 0

思路是有带小数的取整+1,1-小数部分。由于在游标判断的时候有30个字段都需要判断。如果直接写在代码里面就有很多重复代码,造成冗余。

就想到用函数。没写过函数哟,就到网上看了一些例子:

create function GetInt_decimal(
  参数
)
returns varchar(20)  返回类型
as 
begin 
 处理代码
return 返回变量
end 

----------------------------------------------------------------------------------------------------------

很快就遇到一个问题,我是要返回多变量。

后来有个网友提醒用table 和拼字串的方法:(在这很感谢他)

方法一:table

if object_id('GetInt_decimal') is not null
drop function GetInt_decimal
go
create function GetInt_decimal(
 @p decimal(18,8)
)
returns @table table(i int,d decimal(18,8))
as 
begin 
 Declare @Int_Num as int,@decimal_Num as decimal(18,8) 
 if @p-cast(@p as int)<>0
 begin
    set @Int_Num=1+cast(@p as int)--整数
           set @decimal_Num=@p-cast(@p as int)--小数
 end
        else
 begin
           set @Int_Num=@p
           set @decimal_Num=0
 end
 if @@error=0
 insert into @table select @Int_Num,@decimal_Num
return 
end 
方法二:拼字串

if object_id('GetInt_decimal') is not null
drop function GetInt_decimal
go
create function GetInt_decimal(
 @p decimal(18,8)
)
returns varchar(20)
as 
begin 
 Declare @Int_Num as int,@decimal_Num as decimal(18,8),@Int_decimal varchar(20) 
 if @p-cast(@p as int)<>0
 begin
    set @Int_Num=1+cast(@p as int)--整数
           set @decimal_Num=@p-cast(@p as int)--小数
           
 end
        else
 begin
           set @Int_Num=@p
           set @decimal_Num=0
 end
 if @@error=0
        set @Int_decimal=convert(varchar,@Int_Num)+'|'+convert(varchar,@decimal_Num)
return @Int_decimal
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐