Getting DB Server DateTime in application - c#

I am using Entity framework and have 1 field in database AddedDate that is DateTime and not null, so I need to pass DateTime value.
But the problem is I have to pass DB Server datetime. How can I manage in this sceario or how can I get DB Server datatime to pass this.
I need to some unique solution, because I am this on many forms.
Edit: I need DB server Datetime upon insertion/updation in my application so that I can pass to entity framework object.
Thanks

Since you are using entity framework, you can do something like this:
var dateQuery = yourDbContext.CreateQuery<DateTime>("CurrentDateTime() ");
DateTime dateFromSql = dateQuery .AsEnumerable().First();

In general, if you use the entity framework and you use DateTime in a field, it will automatically do the back/forth conversion for you, just the same way it does so for integers, doubles etc.
Unless you mean something special, i.e., a char[40] field that must be filled with a DateTime value of a particular format.

You can get database server date and time by running SELECT GETDATE()) script.
Consider you have a table with 4 colums - the first 3 being strings and the last datetime, You can solve your issue by issueing INSERT SQL like this:
INSERT INTO myTable VALUES ('x', 'y', 'z', SELECT GETDATE())

Can't you use a stored procedure so you can get DB server Datetime very easily.

Just use getdate() in your query. For example:
INSERT INTO your_table (AddedDate, ...other columns) VALUES (getdate(), ...other values)
This basically asks the server to insert its own current date into the field; there's no need for you to retrieve it locally.

Related

SQL DateTime Vs. C# Datetime MinDate

I have a SQL Server database, one of my tables LatestData has a column which is a non-nullable DATETIME, with a default value of 01/01/1970. See code below the the exact T-SQL code for this column.
[MyDateTime] DATETIME DEFAULT (CONVERT([DATETIME], CONVERT([DATE], '1970/01/01 00:00AM', (0)), (0))) NOT NULL
When this table is added into our server code (C#) via an .EDMX data model, the field looks like the following:
public System.DateTime MyDateTime { get; set; }
I add new data to this table through C#, but at the time of adding the row, my MyDateTime column does not have any data.
As the column is Not Null, my MyDateTime field is set to 01/01/0001 automatically.
Trying to add this date to my DateTime column throws the following error:
System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
After doing some research I found that C# Datetime MinDate is 01/01/0001, whereas SQL Server DATETIME's mindate is 01/01/1753 and this is causing the error.
The C# code is passing the 'empty' field as 01/01/0001 to the database which is then trying to convert it. This is obviously unsuccessful.
Is there any way for the database to know to revert to the default value instead of trying to convert the DATETIME firstly, or do so if a conversion fails?
I know that I could set the column in the Datatable to be a DateTime2 or specify a date for this column before adding it via C#, but that doesn't seem like the best way to go about it?
Thanks in advance for any help.
If 1970-01-01 is an acceptable no date set to you, then put it in the C#:
public System.DateTime MyDateTime { get; set; } = new DateTime(1970, 1, 1);
I do think you should consider allowing nulls in the column though, and make it:
public System.DateTime? MyDateTime { get; set; }
You asked for a SQLS-only fix; the only one I can think of right now is to use a stored procedure to do your insert:
--set up an example table with a datetime
create table a(a datetime);
--test that an insert doesnt work out
insert into a(a) values(cast('0001-01-01' as datetime2)); --error!
go
--make a procedure to do the insert logic/conversion
CREATE PROCEDURE a_ins(#a DATETIME2)
AS
BEGIN
INSERT INTO a (a)
--if the date is less than the column will support, default it
SELECT case when #a < CAST('1753-01-01' as datetime2) THEN cast('1970-01-01' as datetime) else cast(#a as datetime) end
END
GO
--quick run the procedure to test
DECLARE #dt2 DATETIME2 = cast('0001-01-01' as datetime2);
EXEC a_ins #dt2 --inserts 1970
You ca choose what range of dates you want to insert - maybe anything before 1970 will become 1970, maybe anything before 1753, maybe only 0001-01-01 .. you choose in the "case when" logic
This is yet another reason why you should prefer DateTime2 over DateTime - The DateTime2 data type supports the same date range as the .Net framework's DateTime struct - from January 1st 0001 to December 31 9999.
Change the MyDateTime data type to DateTime2, and the default value to 0001-01-01:
ALTER TABLE MyTable
ALTER COLUMN MyDateTime DateTime2 NOT NULL
To change the default value constraint you need drop it and re-create it.
This can be easily done using SSMS (just find it, right-click and drop) but using T-SQL you will have use one of the answers from this post since you didn't specify it's name. Once you've done that, you can add it (with a proper name this time):
ALTER TABLE MyTable
ADD CONSTRAINT DF_MyDateTime DEFAULT ('0001-01-01') FOR MyDateTime

DateTime sql server vs. System.DateTime

I have a stored procedure which input is from the type datetime. i.e. I transfer the input
2014-01-13T16:55:03.370 ,while running the stored procedure from the sql server.
Now I want to execute a stored procedure from the application.So I tried to use parameter having System.DateTime type.Looks like it is not corresponds to sql datetime.
Which type should I use for that?
UPD.
I didn`t get the answer for my question. So I`ll try to make my question more clear.
In SQL SErver database tables the values of the type datetime are saved.I am writing a stored procedure which looks for this values .I mean I need to get a parameter from the user of the for yyyy-mm-ddThh:mm:ss:.mmmm
from MSDN:
GetDate() is a inbuilt function in sql, for c# you can use follwing:
DateTime CurrentDate;
CurrentDate = Convert.ToDateTime(DateTime.Now.ToString("dd-MMM-yyyy"));
I guess you can pass this variable through to the procedure call parameters?
or, search the site again and read: Function that creates a timestamp in c#
Here you can find samples on data time conversions between SQL and C#, depending
on the date data types you use

How do I automatically get date when I create a new row in my SQL table?

I am doing a project in school, I have to create a website tool for salesmen to fill what they have done during the day, i.e. amount of quotes, quote sum, orders, order sum etc. I am using Visual Studio 2010, ASP.NET with C# with a SQL database.
I have to create a table with different columns, that I know how. But what I need is to have a column called Date and it has the datatype date. I need it to be filled automatically without having to input it manually. The same date that the new information was added. I have searched for solution in google and other places but I think I am searching with the wrong keywords, hopefully you can help me.
The format I wish for the date to be is DD-MM-YYYY
When you look for SQL default date on Google, the second result you get is this one.
In there, you have a default date example:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
using the DEFAULT keyword.
Create a sql datetime column in the database, and specify a default value of GetDate() or GetUtcDate() depending on which you want. Format is irrelevant on the input side; you will have to use a formatter on the select side (or in your c# code).
You can set the default value for the column as current date time..
create table tblname (
fieldname datetime default getdate()
)
Also see this question
Add default value of datetime field in SQL Server to a timestamp
You can use one of this to insert in the table instead.
String s = System.DateTime.Now.ToString("dd.MM.yyyy");
DateTime now = System.DateTime.Now;
The second one would be your choice because the type specified in yur table is Date.
If don't want to be setting it from the app, specify which database you are using to get a specific answer.

Equality comparison fails between C# datetime and SQL datetime

I am trying to do an equality comparison between a C# datetime and a SQL datetime, which appears to fail due to the precision in which those values are stored.
So say I have a really simple SQL table, with these fields:
ID (PK, int, not null) - identity
Title (text, null)
UpdateTime (datetime, not null)
I create a class object via Entity framework, setting its UpdateTime to DateTime.Now like so:
DateTime now = DateTime.Now;
Title.UpdateTime = now;
When I insert my new object into the table, I see that all the values appear to be stored correctly. Now I want the ID that was created for my object.
This is where things get borked. I try pulling the ID back via LINQ:
Title.ID = context.DBTitles.Where(x=>x.UpdateTime == now).FirstOrDefault().ID;
This throws an exception because the query returns null, despite the fact that the 'now' I've inserted is supposedly the same as the 'now' that was inserted into my table.
So my question : How do I ensure that my C# datetime is equivalent to the datetime stored in SQL? What is the best way to get my ID back?
If you are using SQL server, use DateTime2 instead. It has the same precision as the .NET type.
If you're using Linq, won't the object you're inserting get the ID assigned to it upon commit? You won't need to 'recall' it.

How to convert SQL Server timestamp object to string

I need your help in small problem, I have a column (data type timestamp) in SQL Server 2008.
Now I want to show this timestamp value in ASP.Net C# app as string. Is there any way to do that?
I tried it using regular data fetching in ASP.Net but it produced System.byte[] as output rather than actual value. In SQL Server Management Studio values are represented as 0x000000000000B3C0.
One option is to change it to the Date, while getting from the database. Like:
SELECT timestamp = DATEDIFF(s, '19700101', yourTimestampColumn)
FROM yourTable
I don't know if i catch you, but in sql you can cast timestamp value to datetime then to varchar like this:
declare #val timestamp = 0x0000AAE200B29565
select cast(cast(#val as datetime) as varchar(max))

Categories

Resources