函数/函数返回值和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
转换成功!
各位高手有不同意见请留言,互相进步。。。