//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   ASP.NET 2.0
   Classic ASP 1.0
   Databases
      Access DB & ADO
      General SQL Server & Access Articles
      MySQL
      Other Articles
      Schema Tutorials
      Sql Server 2000
      Sql Server 2005
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
sqlserver2000.databases.aspfaq.com

ASP FAQ Tutorials :: Databases :: Sql Server 2000 :: How do I use GETDATE() within a User-Defined Function (UDF)?


How do I use GETDATE() within a User-Defined Function (UDF)?

SQL Server 2000 added the support for user-defined functions, but there are a few limitations which can be roadblocks at first. One is that you cannot use a non-deterministic function within a UDF, e.g. GETDATE(). So, let's say you are trying to create a function that returns this moment, but a day in the future (e.g. tomorrow at this exact time). You would think about it this way: 
 
CREATE FUNCTION dbo.addDay() 
RETURNS DATETIME 
AS 
BEGIN 
    DECLARE @dt DATETIME 
    SET @dt = DATEADD(DAY, 1, GETDATE()) 
    RETURN @dt 
END
 
But you will get this error message: 
 
Server: Msg 443, Level 16, State 1, Procedure addDay, Line 6 
Invalid use of 'getdate' within a function.
 
So, instead, you should handle it so that you pass non-deterministic values into the function, for example: 
 
CREATE FUNCTION dbo.addDay 

    @dt DATETIME 

RETURNS DATETIME 
AS 
BEGIN 
    SET @dt = DATEADD(DAY, 1, @dt) 
    RETURN @dt 
END
 
Then you can call it like this: 
 
DECLARE @dt DATETIME 
SET @dt = GETDATE() -- or CURRENT_TIMESTAMP 
SELECT dbo.addDay(GETDATE())
 
Another idea is to use OPENQUERY as follows: 
 
CREATE FUNCTION dbo.addDay() 
RETURNS DATETIME 
AS 
BEGIN 
    DECLARE @dt DATETIME 
    SELECT @dt = dt + 1  
        FROM OPENQUERY 
        ( 
            YourServer, 
            'SELECT dt = GETDATE()' 
        ) 
    RETURN @dt 
END 
GO
 
If YourServer is not configured for Data Access, you will get this error: 
 
Server: Msg 7411, Level 16, State 1, Procedure addDay, Line 6 
Server 'YourServer' is not configured for DATA ACCESS.
 
You will need to set the local linked server to allow data access in order to accept calls through OPENQUERY. You can do this using sp_serveroption: 
 
EXEC sp_serveroption 'YourServer', 'DATA ACCESS', TRUE
 
A less efficient (and less accurate) workaround is to use an intermediate view. This simplifies your coding a bit, since you no longer have to pass GETDATE() into the function. First, create the view: 
 
CREATE VIEW dbo.vGETDATE 
AS 
BEGIN 
    SELECT vGETDATE = GETDATE() 
END
 
Then, create the function: 
 
CREATE FUNCTION dbo.addDay() 
RETURNS DATETIME 
AS 
BEGIN 
    DECLARE @dt DATETIME 
    SELECT @dt = [vgetdate]+1 FROM vGETDATE 
    RETURN @dt 
END
 
And you can call it like this: 
 
PRINT dbo.addDay()
 
However, this has been proven to produce inconsistent results, such as this issue that Tibor Karaszi has pointed out: 
 
USE Northwind 
GO  
 
CREATE VIEW dbo.vCurrentDateTime 
AS  
    SELECT gd = GETDATE() 
GO  
 
 
CREATE FUNCTION dbo.getFromView() 
RETURNS DATETIME 
AS  
BEGIN  
    RETURN (SELECT gd FROM vCurrentDateTime)  
END  
GO 
 
CREATE FUNCTION dbo.getFromSelf() 

    @dt DATETIME 

RETURNS DATETIME 
AS  
BEGIN  
    RETURN @dt  
END  
GO  
 
 
DECLARE @dt datetime  
SET @dt = GETDATE() 
 
SELECT DISTINCT dbo.getFromView()  
    FROM Orders o 
    INNER JOIN [Order Details] od 
    ON o.OrderId = od.OrderID  
 
SELECT DISTINCT dbo.getFromSelf(@dt)  
    FROM Orders o 
    INNER JOIN [Order Details] od 
    ON o.OrderId = od.OrderID  
GO  
 
DROP FUNCTION dbo.getFromView(), dbo.getFromSelf() 
DROP VIEW vCurrentDateTime
 
On my machine, the first query produced anywhere from 8 to 10 rows (and this changed with every refresh), while the second query *always* produced exactly one. This is because using a non-deterministic function within the view leads to GETDATE() being evaluated multiple times as the query runs. Now, this is a contrived example, and is unlikely to resemble anything you're doing in the real world; however, I wanted to include this discrepancy for completeness, and in support of using other methods to getting GETDATE() passed into your function. My preference is to use a local variable and pass it into the function from the calling script... 
 

The difference between a deterministic and non-deterministic function is that the former always produces the same output (given the same input), whereas the latter can produce a different output each time they are called (again, with the same input). This is why system functions like GETDATE() are non-deterministic; they will produce different results each time you call them. 
 
In Books Online, there is a topic called 'Deterministic and Nondeterministic Funct...' which goes into much more detail about this issue, and lists the inbuilt functions organized by whether they are always, sometimes, or never deterministic.

Related Articles

Are there tools available for auditing changes to SQL Server data?
Can I create an index on a BIT column?
Can I have optional parameters to my stored procedures?
Can I implement an input mask in SQL Server?
Can I make SQL Server format dates and times for me?
Can I start IDENTITY values at a new seed?
Can SQL Server tell me which row was inserted most recently?
How can I learn more about undocumented SQL Server stored procedures?
How can I make my SQL queries case sensitive?
How do I audit changes to SQL Server data?
How do I connect to a non-default instance of SQL Server?
How do I connect to SQL Server on a port other than 1433?
How do I create a cross-tab (or "pivot") query?
How do I determine if a table exists in a SQL Server database?
How do I drop a SQL Server database?
How do I find all the available SQL Servers on my network?
How do I get a list of SQL Server tables and their row counts?
How do I get rid of Named Pipes / DBNMPNTW errors?
How do I get the correct date/time from the msdb.sysjob* tables?
How do I get the nth row in a SQL Server table?
How do I get the result of dynamic SQL into a variable?
How do I handle REPLACE() within an NTEXT column in SQL Server?
How do I hide system tables in SQL Server's Enterprise Manager?
How do I know which version of SQL Server I'm running?
How do I limit the number of rows returned in my resultset?
How do I load text or csv file data into SQL Server?
How do I manage changes in SQL Server objects?
How do I monitor SQL Server performance?
How do I prevent linked server errors?
How do I reclaim space in SQL Server?
How do I recover data from SQL Server's log files?
How do I search for special characters (e.g. %) in SQL Server?
How do I start SQL Server Agent from ASP?
How do I time my T-SQL code?
How do I upsize from Access to SQL Server?
How do I upsize my MSDE database to full-blown SQL Server 2000?
How do I use a variable in a TOP clause in SQL Server?
How should I store an IP address in SQL Server?
Schema: How do I find all the foreign keys in a database?
SQL Server & MSDE
What are reserved Access, ODBC and SQL Server keywords?
What are the capacities of Access, SQL Server, and MSDE?
What are the main differences between Access and SQL Server?
What do I need to know about SQL Server 2000 SP4?
Where else can I learn about SQL Server?
Where is SP4 for SQL Server 2000?
Why am I having problems with SQL Server 2000 SP3 / SP3a?
Why can't I install SQL Server on Windows Server 2003?
Why can't I install SQL Server on Windows XP?
Why can't I use LIKE '%datepart%' queries?
Why do I get "Login failed for user '\'."?
Why do I get 'object could not be found' or 'invalid object name'?
Why do I get errors about master..spt_values?
Why do I get script errors in Enterprise Manager's 'taskpad' view?
Why do I get SQLSetConnectAttr Failed errors?
Why do I have problems with views after altering the base table?
Why does EM crash when I get an error in a stored procedure?
Why does Enterprise Manager return 'Invalid cursor state'?
Why does my DELETE query not work?
Why does sp_spaceused return inaccurate values?
Why is Enterprise Manager slow at expanding my database list?
Why is my app slow after upgrading from SQL Server 7 to 2000?
Why is tempdb full, and how can I prevent this from happening?
Why should I consider using an auxiliary calendar table?
Why should I consider using an auxiliary numbers table?

 

 


Created: 1/22/2003 | Last Updated: 4/12/2005 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (169)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...