函数/函数返回值和case的使用(返回值)

                                                               函数/函数返回值和case的使用(返回值)

-- =============================================
-- Author:  rorger
-- Create date: 2010-10-19 16:26:36
-- Description: none 时间函数
-- =============================================
CREATE FUNCTION GetDateDiff
(
 -- Add the parameters for the function here
 @datepart VARCHAR(20),
 @startdate datetime,
 @enddate  datetime
)

RETURNS   int
AS
BEGIN
 -- Declare the return variable here
 DECLARE @result INT
 SET @result =CASE @datepart
     WHEN 'minute'   THEN DATEDIFF (minute,@startdate, @enddate)
     WHEN 'second'  THEN DATEDIFF (second,@startdate, @enddate)
     WHEN 'year'      THEN DATEDIFF (year,@startdate, @enddate)
     WHEN 'hour'      THEN DATEDIFF (hour,@startdate, @enddate)
     WHEN 'day'       THEN DATEDIFF(day,@startdate,@enddate)
 END
 
RETURN  @result
END
GO

DECLARE @result INT
DECLARE @datepart VARCHAR(20)
SET @datepart='second'
SELECT @result=dbo.GetDateDiff(@datepart,'2010-10-18','2010-10-20')
SELECT @result

 

 

 

case的注意事项:

不能像使用c语言中的用法那样使用case,

比如c语言风格:

declare @cat varchar

declare @fish varchar

declare @result varchar

set @fish='true'

case @fish

when 'true' then set @result='cat eat fish'

when 'false' then set @result='cat has no fishto eat'

end

 

这样的语句在sqlserver2005中不能通过;

要这样

 

 

set @result=case @fish when 'true' then 'cat eat fish' ...end

 

至于为什么这样:

简单 CASE 函数:

CASE input_expression
    WHEN when_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression

    END

CASE 搜索函数:

CASE
    WHEN Boolean_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression

    END

 

result expression 是任意有效的 SQL Server 表达式。

 

input_expression 和 when_expression必须是相同类型的sql数据类型;

result expression是作为结果值返回的,所以自然不能使用没有返回值的语句如 set 等;

值得一提的是在mssql2005中   case 搜索函数的返回类型在when then 第一条语句就确定了:

看看这个例子:

DECLARE @type INT
SET @type=2

SELECT CASE
WHEN @type=1 THEN  CONVERT(DATETIME,'2010-10-29')
ELSE
    'xxxx'
END
从字符串向 datetime 转换时失败。

 

 

再看一个:


DECLARE @type INT
DECLARE @result INT
SET @type=2

SELECT CASE
WHEN @type=1 THEN  'xxxxx'
ELSE
    3333
END

 

 

结果:

      3333


因此猜测返回类型必须是能够隐式转换或者是第一种情况出现的类型,那么具体情况是不是这样?


DECLARE @type INT
DECLARE @result INT
SET @type=2

SELECT CASE
WHEN @type=1 THEN  'xxxxx'
ELSE
    CONVERT(DATETIME,'2010-8-25')
END

结果:

2010-08-25 00:00:00.000

 

转换成功!

 

各位高手有不同意见请留言,互相进步。。。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值