SQL Update Query: Counting records with current date - sql

I have a column named ClientMigrated of the format 7/23/2019 7:56:45 AM
I have a query that is run within a macro to count the rows where the date portion of ClientMigrated is the current day.
UPDATE Tracking SET Tracking.UserMailboxesMigrated =
DCount("ClientMigrated","[Mailbox Status]","ClientMigrated=Date()")
WHERE (((Tracking.ReportingDate)=Date()));
The query returns nothing because ClientMigrated contains the timestamp part which does not equate to the date.
I've tried to wrap ClientMigrated in a format function so that it compares to Date():
format(ClientMigrated, "dd/mm/yyyy")=Date()
it seems is not acceptable syntax within DCount.
Suggestions to get around this is appreciated.

Consider DATEVALUE to extract the date portion of a date/time field:
UPDATE Tracking t
SET t.UserMailboxesMigrated = DCount("ClientMigrated",
"[Mailbox Status]",
"DATEVALUE(NZ(ClientMigrated, ""1900-01-01"")) = Date()")
WHERE (DATEVALUE(t.ReportingDate) = Date());

Nz should return a date value, not a string, for Null:
UPDATE Tracking t
SET t.UserMailboxesMigrated = DCount("ClientMigrated",
"[Mailbox Status]",
"DateValue(Nz(ClientMigrated, #00:00:00#)) = Date()")
WHERE DateValue(t.ReportingDate) = Date();

You need to utilize the FORMAT function
Assuming that you are using the default value for DATE(), you should be able to use:
UPDATE Tracking
SET Tracking.UserMailboxesMigrated =
DCount("ClientMigrated", "[Mailbox Status]", "ClientMigrated=Date()")
WHERE (((Format(Tracking.ReportingDate, "dd/mm/yyyy"))=Date()));

To use an index onClientMigratedyou should check the datetime field for being same or greater than today (Date()) and smaller than tomorrow (DateAdd(""d"", 1, Date()). The""escapes the double-quote for theDateAddinterval-parameter nested in theDCountcriteria string.
UPDATE Tracking
SET UserMailboxesMigrated = DCount("ClientMigrated",
"[Mailbox Status]",
"ClientMigrated >= Date() AND ClientMigrated < DateAdd(""d"", 1, Date())
WHERE ReportingDate = Date();
ReportingDateis a date not a datetime? If datetime, use same pattern, but you must not escapeDateAdddouble-quotes.

Related

Updating data when date is in condition

I am facing an issue to update the dataset with data type is date in Condition
Script:
UPDATE blse
SET employment = 2066.3
WHERE date = (i am not sure how)
AND industry = 'Total Nonfarm'
AND state = 'Alabama'
;
The Date type formate is YYYY-MM-DD
Example:
SELECT * FROM posts WHERE date = "1982-02-22";
so the command must be like
UPDATE blse
SET employment = 2066.3
WHERE
date = "2022-09-22" AND
industry = 'Total Nonfarm' AND
state = 'Alabama';
I would recommend to use to_date() if you are casting from a string to accommodate a specific format. Example:
SELECT to_date('2000/JUN','YYYY/MON'); -- ok
SELECT '2000/JUN'::date; -- error
Check doc on to_date function:
https://www.postgresql.org/docs/current/functions-formatting.html

Convert string to datetime in cosmos db

In my cosmos db a date field is stored as string like this
{
"ValidationWeekStartDay": "27-Apr-2020"
}
I have to write a query to extract all documents whose ValidationWeekStartDay is greater than current date. How can I achieve this in cosmos db query?
Select * from c wher c.ValidationWeekStartDay > GetCurrentDateTime ()
this does not give me correct result.
This is the problem with date format, the documents you are storing is in format 'dd-MMM-yyyy' while GetCurrentDateTime() function gets the date in format 'yyyy-mm-dd....'. So when you run the above query, comparison like below happens:
'27-Apr-2020' > '2020-08-17'
It compares the characters one by one and first 2 characters of first value becomes greater than second value. For testing purpose, anything above date 20 will be returned by your query irrespective of any month.
There are 2 ways to resolve this.
Store the date in same format as GetCurrentDateTime() function.
Create a udf like below. You can create your own udf, this is just a sample one based on date format.(pardon the formatting, you can copy and run it as it is)
function formatdatetime(datetime){ datetime = datetime.substring(7,11) + '-' + datetime.substring(3,6) + '-' + datetime.substring(0,2); datetime = datetime.replace('Jan','01'); datetime = datetime.replace('Feb','02'); datetime = datetime.replace('Mar','03'); datetime = datetime.replace('Apr','04'); datetime = datetime.replace('May','05'); datetime = datetime.replace('Jun','06'); datetime = datetime.replace('Jul','07'); datetime = datetime.replace('Aug','08'); datetime = datetime.replace('Sep','09'); datetime = datetime.replace('Oct','10'); datetime = datetime.replace('Nov','11'); datetime = datetime.replace('Dec','12'); return datetime; }
And then use the below query:
select c.stdDates as stdDates from c Where udf.formatdatetime(c.stdDates) > GetCurrentDateTime ()

Error "Conversion failed when converting date and/or time from character string " showing for one range and not for another

In my monthly report generation, whenever I update data for some range it gets successfully generated,whereas not for others.
Code 1 (it works):
update warehouse_ticket_header
set resolution_time = CONVERT(varchar(17), resolution_time_duplicate, 120)
where
open_date_time between '03/01/2015' and '05/01/2015'
and config_item like '%Merlin%'
and resolution_time_duplicate is not null
and resolution_time is null
But when I query for June (month number 6), it shows error
Code 2 (Doesn't work)
update warehouse_ticket_header
set resolution_time = CONVERT(varchar(17), resolution_time_duplicate, 120)
where
open_date_time between '03/01/2015' and '06/01/2015'
and config_item like '%Merlin%'
and resolution_time_duplicate is not null
and resolution_time is null
Always use DATETIME datatype and unambiguous datetime format YYYYMMDD format
update warehouse_ticket_header
set resolution_time = resolution_time_duplicate
where open_date_time >= '20150301' and open_date_time <='20150601'
and config_item like '%Merlin%'
and resolution_time_duplicate is not null and resolution_time is null
Since your first query works fine i cant complain the statement rather it should be the data which is causing trouble. I suggest declaring parameters like #startdate and #enddate with data type DATE and assign to the query. This way we are making sure the system uses the strings being provided as date.
Hope this helps!

How do you update a DateTime field in T-SQL?

The following query does not update the datetime field:
update table
SET EndDate = '2009-05-25'
WHERE Id = 1
I also tried it with no dashes, but that does not work either.
When in doubt, be explicit about the data type conversion using CAST/CONVERT:
UPDATE TABLE
SET EndDate = CAST('2009-05-25' AS DATETIME)
WHERE Id = 1
Normally, it should work.
But can you try this? I don't have SQL on my home PC, I can't try myself
UPDATE table
SET EndDate = '2009-05-25 00:00:00.000'
WHERE Id = 1
The string literal is pased according to the current dateformat setting, see SET DATEFORMAT. One format which will always work is the '20090525' one.
Now, of course, you need to define 'does not work'. No records gets updated? Perhaps the Id=1 doesn't match any record...
If it says 'One record changed' then perhaps you need to show us how you verify...
Using a DateTime parameter is the best way.
However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.
e.g.
Given a table created like :
create table t1 (id int, EndDate DATETIME)
insert t1 (id, EndDate) values (1, GETDATE())
The following should always work :
update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic
The following will work :
SET LANGUAGE us_english
update t1 set EndDate = '2010-05-25' where id = 1
However, this won't :
SET LANGUAGE british
update t1 set EndDate = '2010-05-25' where id = 1
This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .
The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.
More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
UPDATE TABLE
SET EndDate = CAST('2017-12-31' AS DATE)
WHERE Id = '123'
If you aren't interested in specifying a time, you can also use the format 'DD/MM/YYYY', however I would stick to a Conversion method, and its relevant ISO format, as you really should avoid using default values.
Here's an example:
SET startDate = CONVERT(datetime,'2015-03-11T23:59:59.000',126)
WHERE custID = 'F24'
That should work, I'd put brackets around [Date] as it's a reserved keyword.
Is there maybe a trigger on the table setting it back?

Update only Time in a mysql DateTime field

How can I update only the time in an already existing DateTime field in MySQL? I want the date to stay the same.
Try this:
UPDATE yourtable
SET yourcolumn = concat(date(yourcolumn), ' 21:00:00')
WHERE Id = yourid;
Try this:
UPDATE t1 SET DateTimeField = CONCAT(DATE(DateTimeField),' 12:34:56');
UPDATE myTable
SET myDateTime = ADDTIME(DATE(myDateTime), #myTimeSpan)
WHERE id = #id;
Documented on MySQl date functions MySQL docs
I have solved in this way:
UPDATE table
SET myDateTime = CONCAT_WS(' ',DATE(myDateTime), CURTIME())
WHERE id = #id;
Obviously you should change CURTIME() with your desired time.
UPDATE myTable
SET myDateTime = ADDTIME(myDateTime, #myTimeSpan)
WHERE id = #id;
For exact syntax of function, see this.
Try this:
UPDATE sms
SET entry_period_end_date= entry_period_end_date+INTERVAL 6 Hour
WHERE TIME(entry_period_end_date) = '06:00:00';
UPDATE `table`
SET time = ADDTIME(time, INTERVAL 13 Hour);
Well, exactly what you are asking for is not possible. The date and time components can't be updated separately, so you have to calculate the new DateTime value from the existing one so that you can replace the whole value.
MySQL DEV page shows functions like subtime and difftime
A sample code to back the time all posts in 3 hours is above:
UPDATE tablepost SET datepost = SUBTIME( datepost , '0 3:0:0' );
Note that values 0 dont alter the respective field. Take care this code, use select first to test these function.
Reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_subtime
Asuming you have a DATE field and TIME field and want to inject the time into the date, try this:
UPDATE mytable
SET mydatefield = ADDTIME( DATE_FORMAT(mydatefield,'%Y-%m-%d 00:00:00'), mydatefield)
WHERE myid = ...
I used ADDTIME in the following way
Earlier in my cloud server, the DateTime was set to UTC but after changing the DateTime to Asia/Kolkata ie UTC 5:30 I wanted the same to reflect in my database tables.
I wanted to update the created_at and updated_at column by 5 hours 30 minutes. I did the following
To update all the rows of the table
UPDATE
products
SET
created_at = ADDTIME(created_at, '5:30:0'),
updated_at = ADDTIME(updated_at, '5:30:0')
You can omit the WHERE condition if you want to update all the records, but since my new records were updated with proper values. So only my rows below id less than 2500 must be updated
UPDATE
products
SET
created_at = ADDTIME(created_at, '5:30:0'),
updated_at = ADDTIME(updated_at, '5:30:0')
WHERE
id < 2500;
This what helped me. I convert time to minutes firstly: 150 for 2:30 am.
UPDATE lesson SET starts_at = DATE_ADD(Date(starts_at), INTERVAL 150 MINUTE)
Minutes are enough accurate for me, though you can use other units: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add