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.
Related
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/
I am building a database application with C# in Visual Studio 2013. The application is meant to email a customer 90 days after the date of their visit so, when they come in, their info is taken and today's date is stored with their other information.
I have a table called Customer ready to store customer information but instead of having the user type the date for each customer and risk them screwing up the format, I would like the default value for the column named DateOfVisit to be today's date.
I am looking for what to type into the default column. Something along the lines of getDate() that will give me today's date in a format that I can easily check against another future date and see if 90 days have past or not.
EXTRA: From the picture, you may notice I have the emailFlag's data type set to bit because I thought that would be the closest thing to a boolean. The purpose of emailFlag is that before a customer is sent an email, that flag will be checked and if it's false the email will go through and the flag will be set to true, so as to avoid spamming the customer emails in case the program messes up. Is this a good idea? Do you have any suggestions as to how I could do it better?
tl;dr
I need a method that will give me today's date to store in a database and that I can compare with other dates.
Try this:
In case you already have the table created
Alter Table dbo.customer Drop Column DateOfVisit;
Lets alter the table and add a field with the deafult value date
Alter Table dbo.customer ADD DateOfVisit DATETIME NOT NULL DEFAULT (GETDATE());
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.
My situation is that we store data in a SQL Server database, supporting 2005 on up. When a DateTime value is stored, it is in the local time of the client. I need to be able to get that date back on any other client, anywhere, without respect to whatever time zone that other client might be in.
So for instance, when a user in New York enters a DateTime value of "2012-12-20 00:00", I want the user in California to see that very same DateTime value. These DateTime values should not respect the difference in time zones, but that is what I see happening. Currently, SQL Server would deliver that DateTime to the California user as "2012-12-19 21:00". Notice how it's now the previous day because of the -3 hour rollback due to the change from EST to PST (forget about DST issues for the purposes of this conversation).
Getting that data back verbatim, and not translated by time zone, is what I need to accomplish. So what advice can you offer?
Some code to consider:
Here is the table:
CREATE TABLE [dbo].[tblMeterReadings](
[fldMeterReadingsID] [int] IDENTITY(1,1) NOT NULL,
[fldMeterID] [int] NOT NULL,
[fldUser] [varchar](50) NULL,
[fldBy] [varchar](50) NULL,
[fldDateOfReading] [datetime] NULL,
[fldReading] [float] NULL,
[fldIsArchived] [bit] NULL DEFAULT ((0)),
We have a Sql class that does the work, and in the following example "sql" is an object of that class. The call is made using a parameterized query where #data0 is the DateTime object to store in a SQL DateTime field:
sql.Execute(#"INSERT INTO tblMeterReadings (fldMeterID, fldDateOfReading) VALUES (" + MeterID + ", #data0)", Date);
Ultimately, this sets up an SqlCommand, assigns parameters, and fires a command.ExecuteNonQuery() call.
Now, to retrieve the date, I simply select it into a DataTable (again, using our Sql class helper):
DataTable myTable = sql.readDataTable(#"SELECT fldMeterID, fldDateOfReading FROM tblMeterReadings");
So what I see is that in the database itself, the date is "2012-12-20 00:00" as I expect, but when I inspect the myTable contents in debug, I see that the date in that table is "2012-12-19 21:00".
The database was created on a SQL Server that runs on a machine in an EST state. My machine, however, is set to PST. Hence the difference in how the DateTime value is delivered to me in the SELECT.
What am I missing?
Store the UTC date in the database. Only convert it to local time when displaying it in a client.
Server side, use getutcdate() instead of getdate().
Thanks to the input from you fine folks, and some research along the lines of your suggestions, we have resolved our issue.
A special thanks to ebyrob for the assistance and this link: http://support.microsoft.com/kb/842545
That link ultimately proved to be the silver bullet.
The fundamental issue is that when you construct a DataTable or DataSet, information about the time zone in which it is created is encoded with it. Then, if you pass that object across a connection to a machine that exists within a different time zone, any DateTime values in there will be adjusted based on the difference in time zones.
In light of that understanding, the fix is to set the DateTimeMode property of all DateTime DataColumns to DataSetDateTime.Unspecified. This prevents the post-serialization date adjustments, instead delivering the DateTime values verbatim.
I also want to point out that the article specifies DataSet, but we have proven DataTable is also vulnerable. In fact, I'm quite certain that it comes down to the DataColumn itself (those with a type of DateTime, anyway). I think the article states this as well.
So thanks again; I think we've got it now!
Anywhere you want to view dates in a certain timezone you can do:
DateTime dtDateOfReading = TimeZoneInfo.ConvertTime(
Convert.ToDateTime(myTables.Rows[i]["fldDateOfReading"]),
dtTimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
);
If you have more than one time-zone you want to view things in, you'll need to store the time-zone with either the date or which customer-site it goes with.
Note: Be careful with the converted DateTime values because they'll have a Kind of Unspecified which may be assumed (incorrectly) to be local in some cases.
EDIT: It might be easier to just set the Timezone for the SQL connection to match the timezone of the SQL Server, but this article: http://support.microsoft.com/kb/842545 seems to indicate that timezone configuration may not be supported by SqlDataAdapter at least.
Is it possible in an easy way to get the NOW() timestamp from an UPDATE query? I'm trying to save the "lastupdated" value in the local cache, or is there in any way possible to get the exact MySQL server time which the update query was executed?
Best Regards; Görgen
To my knowledge, MySQL doesn't have functionality like Oracle's RETURNING or SQL Server's OUTPUT clause to be able to save a query by returning values from INSERT/UPDATE statements. So that means two statements minimum...
is there in any way possible to get the exact MySQL server time which the update query was executed?
The best I can think of is to define an audit column (they were standard approach at my previous work) for logging the timestamp when the record was updated. In MySQL, you can default the value so on update it is set to the timestamp value at that time:
ALTER TABLE your_table
ADD COLUMN update_timestamp TIMESTAMP NOT NULL DEFAULT ON UPDATE CURRENT_TIMESTAMP
...then this gives you a specific column value to query.
The usual way is to set a LastUpdated field in the database, either in the stored procedure or in a trigger. Then you can read it back.