Convert string to datetime in cosmos db - sql

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 ()

Related

Cast function SQL query

I have a column 'Created date' of string type (which has values like 19-01-2022, 05/02/1992 etc). I need to write a query to get the data from this table Orders where created date is greater than Jan 1st 2019. How can I write the query using cast function?
if you have just two string formats i.e. dd-mm-yyyy and dd/mm/yyyy then you can get through inline query only.
SELECT * FROM TABLENAME WHERE CONVERT(DATE,createdDate,103) >= '2019-01-01'
or if you passing search values in dd/mm/yyyy then
SELECT * FROM TABLENAME WHERE CONVERT(DATE,createdDate,103) >= CONVERT(DATE,'01/01/2019',103)
in case if you have more other types of string stored like mm/dd/yyyy then add one column to your table with datetime datatype. you only knowing the type of data in created date so you need to convert them into dates one by one. like for dd-mm-yyyy and dd/mm/yyyy you can convert to date.
Following is example of query for conversion
DECLARE #strdate VARCHAR(50)
SET #strdate = '19-01-2022'
SELECT CONVERT(DATE,#strdate,103)
SET #strdate = '05/02/2022'
SELECT CONVERT(DATE,#strdate,103)
SET #strdate = '12/31/2022'
SELECT CONVERT(DATE,#strdate,110)
you need to update newly added column from createddate column using update query and then apply your function on that
UPDATE TABLENAME SET newcreatedDate = CONVERT(DATE,createdDate,103) WHERE newcreatedDate IS NULL
and perform search query
SELECT * FROM TABLENAME WHERE newcreatedDate >= '2019-01-01'
or if you passing search values in dd/mm/yyyy then
SELECT * FROM TABLENAME WHERE CONVERT(DATE,newcreatedDate ,103) >= CONVERT(DATE,'01/01/2019',103)

Put a date variable in quotes in SQL

I have declared a variable that is getting date from an output activity.
vGetDate= 2021-03-20 and want to use this value in my query to fetch the record after that date. eg: (Select * from ABC where UpdatedDate > vGetDate) . I want to put single quotes to date in order to make it work properly.
Below is my code
declare #date1 varchar(20) = activity.output i.e will return o/p in this format(without quotes) : 2021-03-22
select *
from abc
where format([UpdatedDtTm],'yyyy-MM-dd') > cast(#date1 as datetime).
I am using this but since date1 variable has date without quotes , thats why this where condition is not working fine.
Implied data conversions inside a where clause can be a significant performance and/or reliability issue and should be avoided.
As I don't know anything about the activity.output(2021-03-22) or why you cannot use activity.output('2021-03-22') let's try to consider a simplified case. On the assumption that the column [UpdatedDtTm] is indeed a datetime column, then you can compare that column to a datetime variable without needing format() or cast(), like this:
declare #Date1 datetime = '20210322'
select * from abc
where [UpdatedDtTm] > #Date1
Keep in mind that any date related data types are NOT stored "in a format" they are actually numeric and any format that we use to understand the date or time is applied rather like typing 44279 into an Excel cell and then formatting it to a date which displays as 2021-03-24 (if your default date format is yyyy-mm-dd). It's not exactly the same in SQL Server but quite similar.
I am ignoring activity.output but assuming it is a string. Likewise I am assuming [UpdatedDtTm] is a datetime column.
declare #Date1 datetime = try_cast(activity.output as datetime)
select * from abc
where [UpdatedDtTm] > #Date1
or
declare #Date1 datetime = try_convert(datetime,activity.output,121)
select * from abc
where [UpdatedDtTm] > #Date1
Note that try_cast or try_convert will not fail if the activity.output isn't a valid date but they will return NULL in such cases and your query will return no rows.
Once you have passed the value into #Date1 then you just compare datetime column to datetime variable. Try to ignore anything to do with "format"

SQL Update Query: Counting records with current date

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.

How to format a date store in varchar format

how can i format a date stored in varchar format.
I have saved date in varchar(255) in format dd:mm:yyyy hh:mm:ss. I need to convert or get in the format hh:mm:ss. I do not want to alter the database structure
I tried,
SELECT [FinishingTime] format(varchar(255), [FinishingTime], 120)
In addition to this question:
I would try to alter the database structure. In the Sql database if i use the datetime2(0). Then i have a problem in getting through my groovy code. I have in long i try to convert into dateformat and set in the string and later store in
database.
def time1= time / 1000; here time is in long
def time2 = time1 + 3600 + timeLeft;
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(Finish2, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
machine.setFinishingTime(formattedDate);
Now i use the getter and setter in a class.
public String getFinishingTime()
{
return getPropertyContainer().getString(FINISHING_TIME, "")
}
public void setFinishingTime(String finishingTime)
{
getPropertyContainer().setString(FINISHING_TIME, finishingTime)
}
Now the question is if i use date time instead of string it does not write in my database or i am not able to set through setter.
You don't need a conversations just use substring() function :
select substring([FinishingTime], charindex(' ', [FinishingTime]) + 1, len([FinishingTime]))
from table t;
However, your idea is really bad to store date-time in custom format, it will lead you lots of trouble while data querying.
I assume it is MS SQL
select convert(varchar, FinishingTime, 108)
or
select convert(varchar, FinishingTime, 8)

SAS PROC SQL; - creating DateTime variable

I am trying to create a datetime variable for the past 3 hours... by concatenating DATE variable (in DATE format) and time variable (string hh:mm:ss) within PROC SQL;
Would highly appreciate any help with this!
Example:
APPLCTN_DT = 05NOV2018:00:00:00.000
APPLCTN_TM = 20:04:57
I would like to create a numeric DATETIME field based on the above
Since it looks like your "date" variable is really a DATETIME variable with zero time you perhaps can just add the time part to it?
new_datetime = APPLCTN_DT + input(APPLCTN_TM,time8.);
Or just to be safe you could force the time part of your datetime value to be zero before adding the time part. Here are a couple of ways.
new_datetime = dhms(datepart(APPLCTN_DT),0,0,input(APPLCTN_TM,time8.));
new_datetime = intnx('dtdate',APPLCTN_DT,0) + input(APPLCTN_TM,time8.);
Presuming the _DT variable is actually a datetime value with no exact time portion (thus just the date)).
Use DATEPART to extract SAS date value, INPUT to convert time string to time value, DHMS to construct a target date time value and INTNX to compute a new date time value offset from the target.
data _null_;
APPLCTN_DT = '05NOV2018:00:00:00.000'dt ;
APPLCTN_TM = "20:04:57";
date_part = datepart(applctn_dt);
time_part = input(applctn_tm,time8.);
target_dt = dhms(date_part,0,0,0) + time_part;
target_minus_3hr_dt = intnx ('dthour'
, dhms(date_part,0,0,0) + time_part
, -3
);
target_minus_3hr_exact_dt = intnx ('dtsecond'
, dhms(date_part,0,0,0) + time_part
, -3*60*60
);
format target: datetime20.;
put target_dt ' combined';
put target_minus_3hr_dt ' combined, 3 hours ago';
put target_minus_3hr_exact_dt ' combine, exactly three hours ago (to the second)';
run;
Will show in log
05NOV2018:20:04:57 combined
05NOV2018:17:00:00 combined, 3 hours ago
05NOV2018:17:04:57 combine, exactly three hours ago (to the second)
Actually, your code is close to the result, i think you forgot to transfer SAS date format to display format.
using put function in variable target_minus_3hr_dt & target_minus_3hr_exact_dt,
since the SAS date is shown as numeric so we need to use put function to transfer.
data _null_;
APPLCTN_DT = '05NOV2018:00:00:00.000'dt ;
APPLCTN_TM = "20:04:57";
date_part = datepart(applctn_dt);
time_part = input(applctn_tm,time8.);
target_dt = put(date_part,date9.)||applctn_tm;
target_minus_3hr_dt = put((intnx ('dthour'
, dhms(date_part,0,0,0) + time_part
, -3
)),datetime20.);
target_minus_3hr_exact_dt = put((intnx ('dtsecond'
, dhms(date_part,0,0,0) + time_part
, -3*60*60
)),datetime20.);
put target_dt ' combined';
put target_minus_3hr_dt ' combined, 3 hours ago';
put target_minus_3hr_exact_dt ' combine, exactly three hours ago (to the second)';
run;