Ardavazt
Ardavazt

Reputation: 73

Table-valued Functions - Incorrect syntax near the keyword 'Begin'

I am trying to write a function in SQL, that executes another function depending on the condition. but I am not able to fix the error here.

fn_GetSpecialLastCurrencyRateByDate, Line - Incorrect syntax near the keyword 'Begin'

CREATE FUNCTION [BCF].[fn_GetSpecialLastCurrencyRateByDate]
(   
    @SkinId INT,
    @CurrencyIdFrom char(3),
    @CurrencyIdTo char(3),
    @EndDate datetime
)
RETURNS
TABLE
(
    Id INT,
    CurrencyId char(3),
    ToCurrencyId char(3),
    Rate decimal(24,18),
    Date date
)
AS
Begin
    If (not exists( Select TOP 1 Id, CurrencyId,ToCurrencyId ,Rate , Date date
        From BCF.SkinCurrencyRate
        Where SkinId = @SkinId and CurrencyId = @CurrencyIdFrom AND ToCurrencyId = ISNULL(@CurrencyIdTo, 'EUR')  and Date<=@EndDate
        Order By Date desc))
    BEGIN
        return Select Id, CurrencyId,ToCurrencyId ,Rate , Date date from [BCF].fn_GetLastCurrencyRateByDate(@CurrencyIdFrom, @CurrencyIdTo, @EndDate)
    END
    ELSE
    BEGIN
        RETURN (
        Select TOP 1 Id, CurrencyId,ToCurrencyId ,Rate , Date date
        From BCF.SkinCurrencyRate
        Where SkinId = @SkinId and CurrencyId = @CurrencyIdFrom AND ToCurrencyId = ISNULL(@CurrencyIdTo, 'EUR')  and Date<=@EndDate
        Order By Date desc)
    END
end
GO

Upvotes: 1

Views: 972

Answers (1)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

You should declare your table name like below

RETURNS @Result

Then you need to insert into @Result table instead.

Your entire code should be like this

CREATE FUNCTION [BCF].[fn_GetSpecialLastCurrencyRateByDate]
(   
    @SkinId INT,
    @CurrencyIdFrom char(3),
    @CurrencyIdTo char(3),
    @EndDate datetime
)
RETURNS @Result
TABLE
(
    Id INT,
    CurrencyId char(3),
    ToCurrencyId char(3),
    Rate decimal(24,18),
    Date date
)
AS
Begin
    If (not exists( Select TOP 1 Id, CurrencyId,ToCurrencyId ,Rate , Date date
        From BCF.SkinCurrencyRate
        Where SkinId = @SkinId and CurrencyId = @CurrencyIdFrom AND ToCurrencyId = ISNULL(@CurrencyIdTo, 'EUR')  and Date<=@EndDate
        Order By Date desc))
    BEGIN
        INSERT INTO @Result 
        Select Id, CurrencyId,ToCurrencyId ,Rate , Date date from [BCF].fn_GetLastCurrencyRateByDate(@CurrencyIdFrom, @CurrencyIdTo, @EndDate)

    END
    ELSE
    BEGIN
        INSERT INTO @Result
        Select TOP 1 Id, CurrencyId,ToCurrencyId ,Rate , Date date
        From BCF.SkinCurrencyRate
        Where SkinId = @SkinId and CurrencyId = @CurrencyIdFrom AND ToCurrencyId = ISNULL(@CurrencyIdTo, 'EUR')  and Date<=@EndDate
        Order By Date desc
    END

    RETURN;
end
GO

Upvotes: 2

Related Questions