Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use GetDate() or GetUTCDate() from a User Defined Function?

User-Defined Functions

How to use GetDate() or GetUTCDate() from a User Defined Function?

by  fhlee  Posted    (Edited  )
This FAQ is linked to my other FAQ which helps to return the SQL Server TIMEZONE from a User Defined Function.

Due to SQL determinism; If you try to use the GetDate() or GetUTCDate() function within a User Defined Function, you will get an error message:
Error 443: Invalid use of 'getdate' within a function.
-or-
Error 443: Invalid use of 'getutcdate' within a function.

If you want to return the CURRENT GMT/UTC time on the SQL Server, you need to do:

1. You create VIEW first:
[color blue]CREATE VIEW dbo.SYS_GetUTCDateTime
AS
SELECT GETUTCDATE() AS UTCDateTime
[/color]

2. You create a USER DEFINED FUNCTION:
[color blue]CREATE FUNCTION dbo.fniGetUTCDateTime( )
RETURNS DATETIME AS
BEGIN
DECLARE @vdUTC DATETIME
SELECT @vdUTC = UTCDateTime FROM SYS_GetUTCDateTime
RETURN @vdUTC
END
[/color]

Replace the GetUTCDate() with GetDate() if you just want to return the current server local (system) time.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top