Simulate current date on a SQL Server instance? - sql-server

Is it possible to change the datetime for a particular database on SQL Server?
Is it tied to the operating system's date/time?
We wish to simulate a future datetime for testing purposes i.e. so the GETDATE() returns a date in the future.
It's got to be in a semi-production (staging) environment so unfortunately changing the OS date / time isn't an option for us.
In an ideal world we'd spin up a virtual server, but also not really an option at the moment.

As stated, by others, No.
A really hacky workaround, would be be to write your own function to return the date you want and have it return GETDATE() when you're done testing, and call that function instead. There's probably some slight overhead in doing this, but it'll do what you need.

Unfortunately it is tied to the OS date and time. See here: http://msdn.microsoft.com/en-us/library/ms188383.aspx
This value is derived from the operating system of the computer on
which the instance of SQL Server is running.

You can always use this and adjust accordingly:
SELECT getutcdate()
Please see below for more information
StackOverflow Question
But there is no way to change the results from a GETDATE() without changing the server's date.
Added:
You could do a EXEC xp_cmdshell 'DATE 10/10/2011' if you wish... but it's not advised.

Another workaround I've had some success with is to add an INSTEAD OF trigger to any table where a GETDATE() value is being inserted and modify it there e.g.:
ALTER TRIGGER [dbo].[AccountsPayableReceivable_trg_i] ON [dbo].[AccountsPayableReceivable]
INSTEAD OF INSERT
AS
SET NOCOUNT ON
SELECT *
INTO #tmp_ins_AccountsPayableReceivable
FROM INSERTED
UPDATE #tmp_ins_AccountsPayableReceivable
SET dtPaymentMade = '01-Jan-1900'
WHERE dtPaymentMade between dateadd(ss, -5, getdate()) and dateadd(ss, +5, getdate())
INSERT INTO AccountsPayableReceivable
SELECT *
from #tmp_ins_AccountsPayableReceivable
(Incidentally, the where clause is there because my test script autogenerates these triggers, adding an update for every datetime column, so I only want to update those that look like they are being inserted with a GETDATE() value.)

I believe you can create a user function that would do the calculation for you and apply that.
http://msdn.microsoft.com/en-us/library/ms186755.aspx
Also, it can be used as the default value for a column.
Bind a column default value to a function in SQL 2005

Related

SQL Server 2008R2 alter GETDATE result as a default value

Is there a way to alter the outcome of getdate() while still using it as a default value? E.g. being able to plus or minus x number of hours.
The situation:
a German hosted server (GMT+2) with some end users in Australia (GMT+10). One column is using the default getdate() value therefore is inserting German time. Some code is generating a DateTime based on Australia time so there are 8 hours difference.
The objective:
For several good reasons the aim is to handle this on the database and not touch application code. I would like to add 8 hours onto the German getdate() default database value....... or handle this some other way on the database
you can use default value using DATEADD() function to add 8 hours to the date:
create table dbo.foo
(
dateColumn datetime default (dateadd(hour,8,getdate()))
)
I don't see any such option and it is little dangerous too. You can create a function with the same name GETDATE in your database, but that would require you to prefix with dbo(or schema name) while calling the function.
So, you may need to write your own function and make use of GETUTCDATE() and add delta according to timezone.

insert record when datetime = system time

I am new to sql so bear with me. I want to insert a record into another table when a datetime column = the system time. I know this is an infinite loop. I am not sure any other way to handle what I am trying to solve.
INSERT INTO dbo.Que
(Name, Time)
SELECT ProspectName, ProspectDate
FROM myProspects where ProspectDate = CURRENT_TIMESTAMP
I need to place a phone call at a certain time. I need to insert the record into another table to execute the call when the time = now. If you have a better way of handling this, please tell me.
Thanks
If you are using sql server, you can use the getdate() function.
You would need to insert the createdate into a column of the call on insert, also using getdate() or if using .net System.Datetime.Now
e.g. select all calls that happened in the last x amount of time in SQL server:
select * from calls where createdate > getdate() - .1

Changing the output of Getdate

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!
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.
You can always wrap GetDate() in a custom function and use that everywhere, although it's not an optimal solution.
No, there is not much you can do other than something like this:
SELECT GETDATE()-7 --get date time 7 days ago
SELECT DATEADD(dd, -7, GETDATE())
One approach is to have an optional fake clock.
Create a single row table (I usually call it dbo.System cos I usually have a number of global parameter values) with a column I call mine CurrentMoment which is datetime2 NULL (so the value can be NULL or a datetime).
Create a function to replace GetDate()
CREATE OR ALTER FUNCTION [dbo].GetDate
RETURNS datetime2
AS
BEGIN
RETURN ISNULL((SELECT CurrentMoment FROM dbo.System), SYSDATETIME());
END
GO
-- Yes the above returns a more accurate clock than GETDATE().
Replace ALL references to GETDATE() with dbo.GetDate() - This does require a small change to existing scripts.
With System.CurrentMoment set to NULL all works as normal, real time. But set a value and you have a fake clock, you have to update it as tests/demo proceed.
If you are concerned about performance, you can modify the function so it either returns SYSDATETIME() or the fake datetime as preferred. But I have not found a performance issue worth worrying about.
Alternatively you could have a column in System which is an offset to the current time, and subtract it from SYSDATETIME() when the function is called. That way the value will move on between function calls.

How to alter a DateTime field when it is updated?

Is there a database level function (trigger or something) that I can use to alter a DateTime field when new data is inserted? The issue is that a service I am integrating with happens to send out all of its times (in this case the time some info was received on their end) in GMT.
I need to automatically change this to reflect the time in the timezone the db server is in. For example, if they send me 2:34 PM, but I am in NYC, I would want it to be entered in the db as 9:34 AM. This would also have to account for differences in Daylight Savings between GMT and wherever the server is, which seems like a nightmare. Any suggestions?
Also, I am using SQL Server 2005 if that helps.
EDIT:
Let me clarify one thing. The dates going into this column are retrieved in batches every so often (5, 10, 15 minutes), so I think the only way to go is to alter the time once it has been received, not to add a TimeModified field or something. Is that even feasible?
You could create
a default value for the DateTime which gets set when you insert a new record
CREATE TABLE dbo.YourTable
( ........,
LastModifiedOn DATETIME
CONSTRAINT DF_YourTable_LastModifiedOn DEFAULT (GETDATE())
)
a AFTER UPDATE TRIGGER which sets the DateTime field to the new value whenever you've updated your row
CREATE TRIGGER trgAfterUpdate
ON dbo.YourTable
AFTER UPDATE
AS BEGIN
UPDATE dbo.YourTable
SET LastModifiedOn = GETDATE()
FROM INSERTED i
WHERE i.Table1ID = YourTable.Table1ID
END
With the default value and the trigger, your datetime field LastModifiedOn should always be up to date and showing the last modification date/time.
Marc
Another option here would be to use a calendar table where you map a UTC date and time to the local date and time value.
Disadvantages here are a loss in some of the granularity. If seconds are important I would not implement this; you can look at the size of the calendar record and compare it to the size of storing a datetime for every record in your transactional table. Obviously the smaller the volume the less beneficial this solution will be. Also, if you don't build in automatic and unattended repopulating future records in the solution the table will "run out" of records, and you will have left a time bomb for whoever comes in after you (maybe yourself too).
Advantages though are that you will be able to perform any queries on this table much more quickly (because it is an integer). Also if you ever decide that your NYC server needs to move to Sacramento, you can update the "localDateTime" and leave the UTC time in tact.
Table structure (granularity will be up to your needs):
ID int
utc_month int
utc_day int
utc_year int
utc_hour int
utc_minute int
local_month int
local_day int
local_year int
local_hour int
local_minute int
Yet another option (again depending on volume) is to deploy a managed assembly.
(see this site for instructions, you do have to make a server configuration change. How to implement a managed udf or sp)
Here is the C# that I put in my udf
public static SqlDateTime udf_ConvertUTCDateTime(SqlDateTime utcDateTime)
{
DateTime dt = utcDateTime.Value;
utcDateTime = dt.ToLocalTime();
return utcDateTime;
}
The following code will return you the converted UTC datetime. Just use that value in your insert or trigger.
Declare #D datetime
set #D = GetUTCDate()
select #D
select dbo.udf_ConvertUTCDateTime(#D)
Create a field of the type Timestamp - that will get updated whenever any data is modified in that row. Alas, it's literally a relative timestamp, so it can only be used for versioning. More information can be found here:
http://msdn.microsoft.com/en-us/library/ms182776(SQL.90).aspx
following example should do the job. Add ModifiedOn or similar DateTime field to your db table.
insert into foo (field1, field2, ...., ModifiedOn)
values (value1, value2,...., GetDate())
or for update
update Foo
set field1 = value1,
field2 = value2,
.
.
.
.,
ModifiedOn = GetDate()
Where ....

Change default date time format on a single database in SQL Server

I need to change the date format from US (mm/dd/YYYY) to UK (dd/mm/YYYY) on a single database on a SQL server machine.
How can this be done?
I've seen statements that do this for the whole system, and ones that do it for the session, but I can't change the code now as it will have to go through QA again, so I need a quick fix to change the date time format.
Update
I realize that the date time has nothing to do with how SQL Server stores the data, but it does have a lot to do with how it parses queries.
I'm chucking raw data from an XML file into a database. The dates in the XML file are in UK date format.
You could use SET DATEFORMAT, like in this example
declare #dates table (orig varchar(50) ,parsed datetime)
SET DATEFORMAT ydm;
insert into #dates
select '2008-09-01','2008-09-01'
SET DATEFORMAT ymd;
insert into #dates
select '2008-09-01','2008-09-01'
select * from #dates
You would need to specify the dateformat in the code when you parse your XML data
In order to avoid dealing with these very boring issues, I advise you to always parse your data with the standard and unique SQL/ISO date format which is YYYY-MM-DD. Your queries will then work internationally, no matter what the date parameters are on your main server or on the querying clients (where local date settings might be different than main server settings)!
You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:
set language 'british english'
Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as
1-Dec-2008
Although you can not set the default date format for a single database, you can change the default language for a login which is used to access this database:
ALTER LOGIN your_login WITH DEFAULT_LANGUAGE=British
In some cases it helps.
If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"
Use:
select * from mytest
EXEC sp_rename 'mytest.eid', 'id', 'COLUMN'
alter table mytest add id int not null identity(1,1)
update mytset set eid=id
ALTER TABLE mytest DROP COLUMN eid
ALTER TABLE [dbo].[yourtablename] ADD DEFAULT (getdate()) FOR [yourfieldname]
It's working 100%.
You do realize that format has nothing to do with how SQL Server stores datetime, right?
You can use set dateformat for each session. There is no setting for database only.
If you use parameters for data insert or update or where filtering you won't have any problems with that.
For SQL Server 2008 run:
EXEC sp_defaultlanguage 'username', 'british'

Resources