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

用户定义函数需要传入一个默认参数(当前的月份),却做不到?
CREATE   FUNCTION   fn_myfun(@month   int   =   Month(GetDate()))
RETURNS   float
AS
BEGIN
    ......
END

把GetDate()放在函数内部也不行,请教怎么解决这个问题?

------解决方案--------------------

CREATE FUNCTION fn_myfun()
RETURNS float
AS
BEGIN
declare@month int = Month(GetDate())
...
END

declare
------解决方案--------------------
Ms Sql 的函数功能就是这样,不能接受非确定的函数

改用存储过程吧
------解决方案--------------------
参数是调用函数的时候传递过来的,你不能直接给函数附一个确定的参数,你只要声明一个变量就好
------解决方案--------------------
--定义一个视图,从视图中获取当前月分
create view vwMonth
as select NowMonth=Month(getdate())

go
create function fnTest(@month int)
returns float as
begin
declare @NowMonth int
select @NowMonth=NowMonth from vwMonth
return 1.0*@NowMonth
end

go
declare @n int
select dbo.fnTest(@n)

go
drop view vwMonth
drop function fnTest
------解决方案--------------------
CREATE FUNCTION fn_myfun(@month int)
RETURNS float
AS
BEGIN
......
END

--调用时传过去就行了.
fn_myfun(month(getdate()))