So if I run a virtual instance of IIS on localhost to test some site, I have a datebase field with a default CURRENT_TIMESTAMP that upon insertion always defaults to 1/1/0001 12:00:00 AM, which is, as I understand, the null-like value for DateTime in these scenarios.
Why is this happening? Can't I get the actual time and date to go in this field?
I've tried using getdate(), sysdatetime() and whichever else alternatives and it's the same thing.
The field in the C# code is:
public DateTime LastModification { get; set; }
Any workaround around this?
I'm using the correct mappings as per msdn
Related
I have read several post around the problem but found not solution to the issue I'm facing with.
My entity model contains several date properties whose values I need to be set at SQL server level. Here's an example:
[Column(IsDbGenerated = true)]
public DateTime DateCreated { get; set; }
DateCreated is a 'date' type on SQL Server, and its default value is GETDATE().
[DateCreated] DATE DEFAULT (getdate()) NOT NULL,
As a matter of fact saving a new record (without passing any DateCreated value) results in '1/1/0001' (i.e. null datetime) value being inserted.
It looks like Linq overrides default server GETDATE() value, forcing a 'null' value to be written.
You must use DatabaseGenerationOption.Identity.
Here are two links that explain further:
Entity Framework Code First Data Annotations
How do I tell Entity Framework to allow SQL Server to provide a defined default value for a field?
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.
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
I have generated classes (DbContext) modelling my db (SQL Server 2008 R2), and in most of my tables I have the standard ModifiedDate and CreatedDate (No Nulls). Each of these has a default of getdate() in SQLServer, and I have a trigger to update ModifiedDate on any updates.
The generated views included the ModifiedDate and CreatedDate fields, which I don't want (the user shouldn't see these), so I've taken these out, but when adding a new entry using the generated Create view, I get the error "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value".
I then added some default values, and it did add the record, but naturally it added my entered values, and not the SQL getdate() values, which I'd prefer (I want it to show the server time). Checking the object (db.SaveChanges()) the fields have a value of {1/01/0001 12:00:00 AM}.
How can I use these models without entering dates??? I've searched but haven't found my answer... ;-(
This is a common problem in both Entity Framework and Linq to SQL:
In Linq-To-SQL the model doesn't know about the default values, and so attempts to assign them as "null" - which in this case isn't acceptable. To fix this, open the DBML file and set the "Auto Generated Value" option to "true" for the fields in question.
In Entity Framework it's a little different: you set the "StoreGeneratedPattern" on the field to either "Identity" or "Computed". Here's the description:
http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.storegeneratedpattern.aspx
EF will do this automatically for Identity type fields, but not for default value/not null fields. You may want to set your CreatedDate as "Identity" (updated only on insert) and your ModifiedDate as "Computed" (updated on insert and update).
The byproduct of this is that you then will not be able to set the fields via Linq at all - but that's fine in your use case, I think.
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 ....