SQL Server Current_Timestamp Format - c#

I'm learning SQL Server and have an update statement where the current date and time are inserted as follows:
UPDATE data_table
SET Date_Time_Cx = CURRENT_TIMESTAMP
When it is populated in the DB, it appears "Feb 22 2018 5:07PM". How do I get to populate with the format "YYYY-MM-DD hh:mm:ss"? I looked through the SQL Server documents and lots of posts and it seems like it should be populating in the desired way. Where did I go wrong? Thanks!

Then change the type of date_time_cx:
alter table data_table alter column date_time_cx datetime2;
Then it should go into the database using the proper types. You can format the value as you wish afterwards.

I'm not sure what this has to do with C#, but here's a solution for you using base SQL.
SELECT convert(varchar, getdate(), 121)
You can find all kinds of different date and time formats from the link below.
https://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/

Related

Inserting DateTime to SQL script

I'm writing a SQL script to register components in a database. One of these requires DateTime (from last year) to be inserted as one of the values into a table, like this:
INSERT INTO ComponentTable (ComponentId, Setting, [Value]) VALUES ('id', 'StartDate', ... )
The C# I had previously been using to insert the value was DateTime.Today.AddDays(-365).ToString() (before switching to a database).
Is there a way of adding the same thing into the SQL script above?
Thanks
This article shows and explains the SQL Server date/time functionality you need:
Date and Time Data Types and Functions (Transact-SQL)
In your case, this might work:
INSERT INTO ComponentTable (ComponentId, Setting, [Value]) VALUES ('id', 'StartDate', DATEADD(DAY, -365, GETDATE()))
Note the following:
Previously, you determined the date/time value in your client app (C#), thus using the date/time value of your client computer. When using the SQL Server functionality, the system date/time of the machine running your SQL Server instance will be used instead. (I consider this to be an advantage.)
It is advised to store date/time values in the database in a way that they are not region-specific. So including the time zone might be important if you have multiple clients in different time zones. In my opinion, storing the UTC date/time values in the database (by using GETUTCDATE() instead of GETDATE() and converting the retrieved value in your C# client apps to local time (using the DateTime.ToLocalTime() function) might be useful.
I tried the following, this gives you the date 365 days ago; is this what you want?
CREATE TABLE test (ID serial PRIMARY KEY, startdate DATE);
INSERT INTO test (startdate)VALUES (date(now()) - integer '365');
See the docs: https://www.postgresql.org/docs/9.0/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
If you want exactly one year (taking care of leap years) then you would probably need to use 'extract' to get the year, then subtract one, and reconstruct the date.

Properly Format DateTime on XML Datetime

I am trying to serialize an entity using XML serialization on SQL. Unfortunately I notice that my datetime is not properly read. I am returning a 24 hour format, but on SQL, its reading a different time. Here is the exact SQL Stored Procedure:
DECLARE
#XML XML = '- <ArrayEntityView>
- <entEntity>
<dtModifiedDate>2017-07-24T14:09:20.4483795+08:00</dtModifiedDate>
</entEntity>
</ArrayEntityView>'
DECLARE #tblProcAssign TABLE
(
dtmoddate DATETIME
)
INSERT INTO #tblProcAssign
(
dtmoddate
)
SELECT entuserunits.value('dtModifiedDate[1]', 'DATETIME') AS dtModDate
FROM #XML.nodes('ArrayEntityView/entEntity')entUserUnits(entuserunits)
select * from #tblProcAssign
Based on the code above, I am passing a date:
2017-07-24T14:09:20.4483795+08:00
But on SQL, its reading is:
2017-07-24 06:09:20.447
And I am not sure why, it should be:
2017-07-24 14:09:20.447
The data came from c# code DateTime.Now. I don't want to use GetDate in SQL since sometimes, I am not using DateTime.Now. How should I format this entity or any parsing I need to do so that I will get my expected result?
You need to switch the data type from datetime to datetimeoffset if you want time zone information to be recognised. Without it, only the actual time value (that is, UTC) is returned.
Make sure that the data type is replaced in both the table definition and the XML value() method:
DECLARE #tblProcAssign TABLE (dtmoddate datetimeoffset);
INSERT INTO #tblProcAssign (dtmoddate)
SELECT entuserunits.value('dtModifiedDate[1]', 'datetimeoffset') AS dtModDate
FROM #XML.nodes('ArrayEntityView/entEntity')entUserUnits(entuserunits);

Convert C# Datetime to 0000-00-00 00:00:00 to MySQL

DateTime field is 'not null' in Table Structure but I want to store data (MVC C# Datetime) 0000-00-00 00:00:00 to MySQL Table without changed table structure.
I Try to do this but its but ERROR!!
Convert.ToDateTime("0000/00/00");
Please HELP , Thanks
The minimum value for .NET DateTime is January 1, 0001; the minimum for MySQL DATETIME is '1000-01-01', but in case of SQL MODE it is possible to insert '0000-00-00' as DATE, see NO_ZERO_DATE in documentation.
If you want to store '0000-00-00' in .NET DateTime structure, then use '0001-01-01', then if it is possible change this value in representation layer.
If you want to store '0000-00-00' in MySQL, then you should check SQL MODE in MySQL server -
SELECT * FROM information_schema.GLOBAL_VARIABLES
WHERE VARIABLE_NAME = 'sql_mode';
From documentation: NO_ZERO_DATE - In strict mode, do not permit '0000-00-00' as a valid date. You can still insert zero dates with the IGNORE option. When not in strict mode, the date is accepted but a warning is generated.
Server SQL Modes
You need to insert those values as string
Like this
Create table tbl(dt datetime);
Insert into tbl values('0000-00-00 00:00:00');
SELECT CAST(dt as char) FROM tbl
Fiddle
If you're asking how to create a C# DateTime object with 0000-00-00 00:00:00 - you can't, it's an invalid date. You could use DateTime.MinValue though. From memory that's 0000-01-01 00:00:00
Why not use NULL? Using magic values instead of NULL is not always a good idea.

String to date in MS Access SQL statement gives type mismatch error

Currently doing a data migration from a Microsoft Access database to a Microsoft SQL Server database using C#. I am trying to create a query to pull data from the Access database and order by two columns: Surname and Date. The challenge is that Date is a string in the following sample format: 12.01.13 (i.e. YY.MM.DD), which is supposed to represent the 13th of January 2012. So I tried the following query in Access:
SELECT * FROM [Contacts 2012]
order by Surname, CDate(Format(Date, "0000-00-00"));
However, I receive this error:
Data type mismatch in criteria expression
So I figure I am getting close. I tried a few different formats, plus maybe DateValue, but to be honest I can't remember. I have looked at other posts both in and outside of stackoverflow, but to no avail.
You said your dates are strings in YY.MM.DD format. If that is correct for all the stored [Date] values ... which means Len([Date]) = 8 for all rows ... those values will sort in the same order whether you sort them as text or transform them to Date/Time values.
So I'll suggest this query ...
SELECT *
FROM [Contacts 2012]
ORDER BY Surname, [Date];
If that returns what you want, you can avoid the data type error you're getting when attempting to transform the strings to actual dates. Also, with an index on the [Date] column, the query will execute significantly faster.
Note this approach is not suitable if some of your [Date] values are not in YY.MM.DD format, eg "12.1.13".
Use Regex.Replace for date format and Regex.Split to add 2 digits to year.
Unsure how i actually finally resolved this but if memory serves i actually sorted the database manually by opening the database in access naturally and sorted by the surname column alphabetically and then sorted by the date column either manually or through a select statement.

Formatting SQL friendly Date/Times in C#

I am building some test scenarios for my application. In order to do this, I have some code that is generating some SQL to help me test properly. A sample of the SQL that is generated is shown here:
INSERT INTO MyTable
(
[ID],
[Name],
[CheckInDate],
[CheckOutDate]
)
VALUES
(
1,
'A title',
'Sat, 17 Dec 2011 14:33:12 GMT',
'Sat, 17 Dec 2011 15:13:12 GMT'
)
When I attempt to execute this SQL, I receive the following:
Conversion failed when converting date and/or time from character string.
How can i format the date/time strings so that SQL Server 2008 will accept them? I really need my C# code to generate the SQL (including the date/time items) to create my tests properly.
Thank you!
The way to solve this is to use the ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion) - note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
You can use SqlParameters.
So your command would be:
INSERT INTO MyTable
(
[ID],
[Name],
[CheckInDate],
[CheckOutDate]
)
VALUES
(
1,
'A title',
#CheckInDate,
#CheckOutDate
)
And you'd insert the dates like so:
SqlParameter checkin = new SqlParameter("#CheckInDate", SqlDbType.DateTime);
SqlParameter checkout = new SqlParameter("#CheckOutDate", SqlDbType.DateTime);
checkin.Value = DateTime.Today; // Format these to the desired dates
checkout.Value = DateTime.Today;
command.Parameters.Add(checkin);
command.Parameters.Add(checkout);
A better approach would be to not format dates at all, parameterize your insert statement, and pass dates as command parameters.

Categories