views:

137

answers:

3

Is it possible to deceive SQL Server to return a different date on GetDate() without actually changing the machine date?
This would be great, since we have a database with old data and I'm trying to test some queries that use getdate().
I can change my machine date but that brings some other problems with other applications...
Any tips?
Thanks!

+2  A: 

You can always wrap GetDate() in a custom function and use that everywhere, although it's not an optimal solution.

klausbyskov
how can you do that? even if you create a UDF it would be `dbo.GETDATE()`
KM
@KM: You would change the implementation of the function so you could change it everywhere modifying one place.@Klausbyskov: If I'm not mistaken you can't have a non-deterministic function like GetDate in a UDF.
JoshBerke
KM is correct, it would only then be used by specifying dbo.getdate() , it doesn't override / replace the built in function.
Andrew
@Josh: You cannot call a UDF without a schema prefix, like **dbo**.GetDate. And you can have non-deterministic functions in a UDF: `create function dbo.GetDate() returns datetime as begin return (select GETDATE()) end` compiles fine
Andomar
@Josh, how do you `change the implementation of the function`? isn't `GETDATE` part of some DLL or EXE inside of SQL Server? and I don't think SQL Server is open source ;-)
KM
@Andomar: I know SQL Server 2000 didn't support calling a non-deterministic function from. Looking in 2008 docs I don't see that listed as a limitation so I guess they changed it. @EveryoneElse: You could write a function called GetMyDate() which you would then update your code to use GetMyDate(), now when you want to hardcode it you can swap the body of GetMyDate()
JoshBerke
+3  A: 

According to the documentation for getdate():

This value is derived from the operating system of the computer on which the instance of SQL Server is running.

Since it's derived from the OS, I don't think you can change it separately.

Andomar
+1  A: 

No, there is not much you can do other than something like this:

SELECT GETDATE()-7  --get date time 7 days ago
KM