I am using Document DB stored procedure to retrieve telemetry time based data into my C# web application. I am having 1000 of documents in my collection. I want to do calculations based on Date Time object. I want to get all documents based on time interval. Using SQL query i am getting result of last 24 hrs records.
SqlQuerySpec query = new SqlQuerySpec("SELECT * FROM c where (c.logdatetime between '" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-ddTHH:mm:ssZ") + "' and '" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ") + "')");
I want to write same query using Stored Procedure. How to do it in Stored Procedure. Thanks in advance.
First of all: I would advise you against performing your queries against a formatted DateTime string. Store the values as "ticks" (seconds or milliseconds since epoch, also known as Unix Time).
Current time in ticks:
// C#
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
// JavaScript
new Date().value
If you want to go back 24hrs, just substract the equivalent ticks from the time. 24 * 60 * 60 * 1000
Second of all: At the very least get rid of the timezones. Your implementation seems to be highly reliable on having only one timezone. Ever. Your writing clients and the CosmosDB server would need to run in the same timezone, guaranteed. Please use DateTime.UtcNow instead of DateTime.Now. Or DateTimeOffset.
(If you are not manually calling ToString before writing your data to CosmosDB, it will already have been stipped of the timezone, see Creating and comparing dates inside CosmosDB stored procedures)
// C#
DateTimeOffset.UtcNow.ToString("s");
// JavaScript
new Date().toISOString();
This is a sample stored procedure:
https://github.com/Azure/azure-documentdb-js-server/blob/master/samples/stored-procedures/SimpleScript.js
function simple(prefix) {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r',
function (err, feed, options) {
...
});
}
It feels like you are trying to ask how to translate your code into JavaScript.
SqlQuerySpec query = new SqlQuerySpec("SELECT * FROM c where
(c.logdatetime between '" + DateTime.Now.AddDays(-1)
.ToString("yyyy-MM-ddTHH:mm:ssZ") + "' and '" + DateTime.Now
.ToString("yyyy-MM-ddTHH:mm:ssZ") + "')");
Which would be something like this using ticks:
var now = new Date().value;
var yesterday = now - 24 * 60 * 60 * 1000;
var query = "SELECT * FROM c where (c.logdatetime between '" + yesterday + "' and '" + now + "')"
If you need to keep the strings:
var now = new Date();
var yesterday = new Date(now.value - 24 * 60 * 60 * 1000);
var query = "SELECT * FROM c where (c.logdatetime between '" + yesterday.toISOString() + "' and '" + now.toISOString() + "')"
Not sure how perfect this behaves when daylight savings time comes into play, but you should find plenty of resources for that if that is critical for you.
Related
Help as early as possible please
I have a form in which I add Exhibitions in the museum name, the date through the Datetimepicker and people came up and then they are saved in the sql database And then on another form I want to select 2 dates in two Datetimepickers and to show in the datagrid that there are some exhibitions between two dates BUT it does not show me correctly, I can not even explain whats wrong
private void button3_Click(object sender, EventArgs e)
{
string period = "SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString() + "' AND '" + dateTimePicker2.Value.ToString() + "'";
LoadData(period);
dataGridView2.Columns[0].Visible = false;
/*dataGridView2.Columns[1].Visible = false*/;
dataGridView2.AllowUserToAddRows = false;
button1.Enabled = true;
}
is it right?
i want it show like events between 12.November.2020 and 21.December.2020
I think you can just use the answer from this question here.
Basically, you just need to feed it the proper format:
string period = "SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") + "' AND '" + dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
For bonus points you could also switch to using string interpolation to make it more readable.
string period = $"SELECT* FROM vistavka WHERE Date BETWEEN '{dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")} ' AND '{dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")} '";
Update:
Please check out this on why doing it this way is a security problem.
Then learn about SQL parameters here.
And finally you can see this answer for how to do date parameters. Basically, you shouldn't have to convert a C# datetime to a string just to pass it into SQL. C# already has mechanisms for this and for good reason, as you'll see in those links.
the date to string convertion was used is wrong
"SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString() + "' AND '" + dateTimePicker2.Value.ToString() + "'";
ToString() format is culture depended and should not be used
You have to pass SQL query with parameters and parameter values (as DateTime objects) to convert date from DateTime by SQL client API to the parameter value format used by your SQL server.
Please find MS SQL sample here
I'm trying to get the records between two dates. Specifically between the start of the day and the time now. This is my query but it doesn't work for me. I have a MYSQL database
var query = (SELECT * FROM `jobs` WHERE `EventTime` < NOW() AND `EventTime` >= '" + dtstartofday + "' AND `PersonSel` = '" + personassigned + "' AND `PersonID` = '" + id + "'");
dtstartofday is of DateTime type.
You're using string concatenation to put query values directly into your SQL string. Don't do this, for a variety of reasons, one of which is the problem you're seeing here - how c# chooses to format the date as string, according to your regional preferences, and how MySQL chooses to parse the string as a date will have direct consequences for how the query runs. As a coarse example, if your date goes in as '2/3/2000' meaning third of feb, you could be using a mysql that interprets it as second of March. Alternatively you might find that c# is representing the date as something mysql doesn't recognise as a date so it is instead converting the EventTime date to a string and then comparing the strings, which is very unlikely to work out (and slow, because of all the conversions)
Either adjust your query so the start of day calculation is done by the db, and parameterize the other elements of your query:
var query = "SELECT * FROM `jobs` WHERE `EventTime` < NOW() AND `EventTime` >= CURDATE() AND `PersonSel` = #personSel AND `PersonID` = #personID"
Or parameterize the start date properly rather than passing its value as a string:
var query = "SELECT * FROM `jobs` WHERE `EventTime` < NOW() AND `EventTime` >= #eventTimeFrom AND `PersonSel` = #personSel AND `PersonID` = #personID"
To add values for the parameters you declare its name, type and value:
var cmd = new MySqlCommand(query, connection);
cmd.Parameters.Add("#eventTime", MySqlDbType.DateTime).Value = dtstartofday; //dtstartofday is a c# datetime representing midnight today e.g DateTime.Date
cmd.Parameters.Add("#personSel", MySqlDbType.Int).Value = personassigned;
cmd.Parameters.Add("#personID", MySqlDbType.DateTime).Value = id;
var x = cmd.ExecuteReader();
It is important to appreciate the difference between having the server do the time and your local machine do the time, especially if they are in different zones, but even if their clocks drift just a little. At some moment what each machine thinks of as "today" will differ. Consider it carefully
Later, when you're bored of writing this kind of code endlessly, you can install Dapper, an extension that does it for you. Take a look at http://dapper-tutorial.net for examples of how it will reduce code like this to just two lines; query and variables in, usable objects out.
I'm trying to update a DATE (not DATETIME) column in SQL Server, but when I execute the SQL command, it is posted with time format also.
string datetosql = "10.4.2015";
string sqlQuery = "UPDATE tbl_tasks " +
"SET description = '" + tbTaskDescription.Text + "', " +
"deadline = '" + datetosql + "' , " +
"status = '" + statusIndex.ToString() + "' " +
"WHERE tid = " + _TaskID;
When I later collect the date using SqlDataReader, it is posted with time format: 04.10.2015 00:00:00. Why is this happening?
.NET doesn't have a date only data type.
If you ask to return a SQL Server date, or a time, it always returns a DateTime struct instance in .NET. For a date, the time properties (hours, minutes, etc.) will be 0.
Note that using queries that aren't parameterized is considered bad! You are open for SQL injection, and you make your life harder since you need to escape quotes, etc.
Add a cast to datetosql, ex:
Cast(datetosql as Date)
I want to store time 11:22:33 in table, but the time is stored like this 112233. How to insert : between the string
String text = "txtucrtime.Text,HH:MM:SS";
var split = Regex.Split(text, #"(?<=[:::])");
See this question: Best way to store time (hh:mm) in a database
Assuming you want to store the time of day, store as an integer which represents the smallest precision you want. If you want to store time in seconds:
hours * 60 * 60
+ minutes * 60
+ seconds
If you want to store to the millisecond, multiple each of the values by 1000 prior to adding them, then also add the milliseconds portion of your time value.
String text = hrs + ":" + mins + ":"secs;
try these thanks
I was trying to make excel graphs using query in c# and I need to collect data for the last month. I am using the following code and its not giving any error but its not giving any result either.
Basicaly I have the data in excel sheets and using that data im making graphs.
First im geting the two dates and converting them to short string and then im matching the strings with the dates picked from excel in the short strong format.
If anyone could answer, I would really appreciate help.
Thankyou,
THE CODE:
// Get current date and time
DateTime dtx = DateTime.Now;
string Date = dtx.ToShortDateString();
// Calculating the last month's date (substracting days from current date.)
DateTime lastmonth= DateTime.Today.AddDays( -30 );
string Date2 = lastmonth.ToShortDateString();
OleDbCommand objCmdSelect = new OleDbCommand(
"SELECT [Hour],(Format(Date, 'Short Date')) AS text_Date,[U_CSSR] FROM [" + excelSheets[j] + "] WHERE CI=" + id + " AND (Format(Date, 'Short Date'))BETWEEN "+ Date + " AND "+ Date2 + " ", objConn);
I think your WHERE clause is logically incorrect. it should be
... BETWEEN "+ Date2 + " AND "+ Date ...
The earlier date should come first.
BETWEEN a AND b is equal to: x > a and x < b.