SQL函数问题与max和代码

时间:2014-03-25 11:49:30

标签: sql sql-server-2008 function

我正在尝试在sql中创建一个函数,但它不起作用,它接受@year int的参数,返回money的数据类型,使用@year返回Ref_table落在@yearbegin_year之间的end_year金额。如果没有值,则返回金额 Ref_table end_year的{​​{1}}最高@year

这是我的代码: -

CREATE FUNCTION fn_year(
    @year int 
)

RETURNS money
as
begin

declare @begin_year int
declare @end_year int
declare @amount money

select  @begin_year = begin_year,
            @end_year = end_year
from DBO.REF_Table
if @year between year(@begin_year) and year(@end_year)
    select @amount = amount
    from dbo.REF_Table
end
else if @amount is null
begin
    select @amount = amount
    from dbo.REF_Table
    where max @end_year
    and @end_year < @year
end
End
GO

1 个答案:

答案 0 :(得分:0)

试试这个,

select top 1 @amount = amount from myTable
where @year <= end_year
order by end_year desc