how to use getdate in user defined function

  • hi,

    I want current year and month like YYMM in user defined function. How can i achieve this one.

    Thanks in advance.

    rgds,

    venkat

     

  • Both of these functions are not deterministic. Therefore, they cannot be used inside a UDF. You can work around this by putting them into a view and then referencing the view inside the UDF:

    create view MyView

    as

    select getdate() as TheDate

    go

    create function dbo.MyFunc ()

    returns datetime

    as

    begin

    return (select * from MyView)

    end

    Thanks,

    Ganesh

  • You could also try this:

    CREATE FUNCTION DBO.fnYearMonth ( @Date DATETIME )

    RETURNS VARCHAR(4)

    AS

    BEGIN

     DECLARE @Verdi VarChar(12)

     Set @Verdi = SUBSTRING(CONVERT(VARCHAR(12),@Date,12),1,4)

     IF @@ERROR > 0

      Set @Verdi = ''

      

     RETURN @Verdi

    END

     

    SELECT DBO.fnYearMonth(GetDAte())

    - Result : 0408

     


    Regards,

    Anders Dæmroen
    epsilon.no

  • hi Ganesh,

    Thanks for the reply. Can you please tell me, how to call a user defined function in a trigger.

    rgds,

    venkat

  • You could also use:

    replace(convert(char(5), getdate(),11), '/', '')

    which would mean that a UDF isn't needed, unless you really want one. If you are using a UDF you could pass this as a parameter.

    Peter

     

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply