use Datetime to do a query in SQL database - sql

I need to retrieve a tuple from the database that have a DateTime as a primary key, the problem i'm having is that it's only working with Datetime's that have the time before midday, otherside it fails to retrieve anything, here is the code:
string fecha = "22-11-2016 15:56:50";
DateTime myDate = DateTime.ParseExact(fecha, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
modelo.solicitud = BD.Solicitud.Find(myDate);
in resume I get a null in modelo.solicitud
if the string fecha is like "01-01-2017 09:00:00" (before midday) it success to retrieve from database, but if it's like "01-01-2017 16:00:30" will fail to retrieve a thing..
Any help of recomendation will be appreciated..

Regardless of the DBMS you are using, fields (columns) that are defined as DATETIME are stored as a binary value. What you see is a generated string representation of the binary value according to either the defaults defined for the DB or a specific format you define for presentation.
You can try setting the default datetime format to something like 'yyyy-mm-dd hh24:mm:ss' (hh24 is Oracle's way to say that you want the hours part to be in the 0-23 range; you will need to check how this is done in your case).
This format also removes ambiguities related to the American/European way of writing dates (i.e. mm/dd/yyyy in the US vs. mm/dd/yyyy in Europe, such that 3/4/16 would mean March the 4th 2016 in the US but April the 3rd 2016 in Europe).
Last, the Spanish word resume has a different meaning than in English (you would normally say summary).
Hope this is clear for you now.

Related

Insert date and time in formats mm/dd/yyyy and time in the format hh24:mm:ss in plsql

Lets say I have a table Student with columns Name,DOJ,TOJ.
Inorder to enter date in mm/dd/yyyy format and timestamp in the format hh24:mm:ss I used ALTER SESSION SET NLS_DATE_FORMAT='MM/DD/YYYY' and ALTER NLS_TIMESTAMP_FORMAT='HH24:MI:SS' but i want to know an alternative solution to enter in this format without involving session. Please guide me through this.
CLICK HERE TO VIEW COLUMNS AND THEIR DATA TYPES
We store dates/times either in a DATE column (which is Oracle's inappropriate name for a datetime) or a TIMESTAMP column (which has more precision and can handle timezones, too). These types have no format. This is important, because thus comparing and sorting them in the database works fine, because the DBMS knows how to handle datetimes, while the users see the date in their format. I, for instance, have set my Windows to German, so I will see the datetimes in some German format, while you will see the same date in a format you are used to.
There are few situations where you want to store date and time separately. The reason is typically that you can set them null. A date without a time means "the whole day". A time without a date means "every day this time". But then you often want this even more advanced anyway ("every Tuesday and Wednesday", "every December 24", etc.) for which you need soemthing more sophisticated then just date and time split into two.
So, usually we just store date and time combined. For a precision down to seconds we use DATE. If we wanted them separately we'd have to think of an appropriate data type, because Oracle has no real date type and no time type either. So we'd either use DATE and ignore the date part or the time part or we use strings. The former solution is usually preferred, because you cannot mistakenly enter invalid data like February 30 or 23:66:00.
If you want to store formatted dates and times, you are talking about strings. I don't recommend this. Strings are not the appropriate data types for dates and times. And a format '01/02/2000' is ambiguous. Some people will read this as February 1, others as January 2.
If you wanted to do this, you would have to change the column types to VARCHAR2 and simply store values like '02/25/2021' and '13:28:56'.
But if you wanted to sort your data or compare dates/times then or just show them to a foreign user in a format they are used to, you would always have to convert them. E.g.:
select *
from mytable
order by to_date(doj || ' ' || toj, 'mm/dd/yyyy hh24:mi:ss');
I am afraid that to change default format you have no other option but to change NLS_DATE_FORMAT either in database level or session level.
But If your purpose is to show the date in a specific format in the front end then you can use to_char() function as below:
SELECT NAME, to_CHAR(DOJ,'dd/mm/yyyy'),to_CHAR(TOJ,'HH24:MI:SS') FROM table
To change the default date format in system level:
ALTER SYSTEM SET NLS_DATE_FORMAT='DD/MM/YYYY' scope=both;
You can also change the default date format at startup time with a login trigger to change the nls_date_format:
CREATE OR REPLACE TRIGGER CHANGE_DATE_FORMAT
AFTER LOGON ON DATABASE
call DBMS_SESSION.SET_NLS('NLS_DATE_FORMAT','YYYYMMDD');

vba access Dlookup with dates in dd/mm/yyyy forma

I'm trying to get a value using a DlookUp, the problem is access formats my dd/mm/yyyy into mm/dd/yyyy despite using the Format function.
muestraAguasDatos = Nz(DLookup("[name]", "samples", "[location] = '" & location & "' AND ([name] LIKE
'*ACRT*' OR [nombre] LIKE '*CAWQ*') AND [sample_date] = #" & Format(sampleDate, "dd/mm/yyyy") & "#"))
This DLookup works when day value are > 12 but when it's lower and despite having the format it still format it to mm/dd/yyyy
Can you help me solving this issue please?
There are so many misunderstanding with MS Access date fields for non-US residents.
The basic rule is :
Whenever you specify a hardcoded date literal using #the date# notation, in
either :
an SQL query
a query filter criteria
in VBA
in a Dlookup() like you do
You should ALWAYS use the US date format : MM/DD/YYYY, or the ISO format YYYY/MM/DD
The confusion among Access beginners, comes from several things :
In the interfaces, by default, MS Access does an implicit conversion of the dates in the format that is defined on Windows Regional and Language Options setting of the computer. So non-US residents might have the impression that dates are always stored by default in the DD/MM/YYYY format, but that cake is a lie. Dates are stored as numbers, and it is just the display format that changes and is adapted following the computer settings.
In some cases, when you code date literals with #the date# in VBA or a Query, using DD/MM/YYYY format, it just works fine. The reason is date there's a check date algorithm in MS Office that validates a date and modify it to the right format in certain circumstances:
When your date begins by the year, MS Access is smart enough to detect it and it will then consider that your date is enterred in YYYY-MM-DD and do an implicit convertion to MM/DD/YYYY.
If the month part is higher than 12 and lower then 31, then MS Access will understand that this is in fact a DAY, and that you hardcoded the month at the other place. So for instance if you introduce 15th of September like this : #15/09/2019# it will implicitly be transformed in #09/15/2019#. However if you enters the 11th September like this #11/09/2019#, then Access will process it as 09th November !!!
Personal opinion, I have always found this last behavior plain stupid, because it may introduces a lot of troubles on applications of people not acquainted by that mechanism, and that tracking where the problems comes can be very tedious. It's sneaky, it should not be there. Much better to raise an error if the format is wrong.

Specify string date format before casting in a function SQL

I have a scenario to cast string date into date format. But the date string is not in a straight format, so the conversion throws error. So what I tried is
set dateformat dmy
before the casting in sql and it worked without any issue.
But the trouble is I need this to implement in a view or function. But the disappointing part, function or view doesn't support set dateformat with which it says as side effecting operator
So how can I specify the date format of the given string before casting in a function or view?
The third parameter of CONVERT() allows to provide a format type.
Assuming your SET DATEFORMAT DMY I take you've to deal with dates like "1/2/2000", meaning the first of February in 2000.
Try this:
DECLARE #d VARCHAR(100)='1/2/2000';
SELECT CONVERT(DATE,#d,104)
The 104 is the German type with a 4-digit year. If this does not fit your needs, you can follow the link to find a better suiting format.
If you need further help, please provide samples of your actual dates.
Hint: You should always store a value in a column with the appropriate type. Storing dates as strings will make things slow and opens a lot of error sources...
As Damien wrote in his comment to the question, ideally you should not mess around with string representations of datetime in the first place - you should be using proper data types - and since you asked about creating a view, it can only mean that somewhere in your database there's a datetime value stored as a string.
The solution to this situation is to change the way you are storing this value - use DateTime2 for datetime values, Date for date-only values, or Time for time-of-day values.
Further reading - Aaron Bertrand's Bad habits to kick : choosing the wrong data type
Assuming you can't change the database design, read the rest of this answer.
You can't use set dateformat on a view or a function, but you can use convert instead of cast to change the string representation of a datetime value into an actual datetime value, assuming the string representation has one of the supported date formats (there are quite a few of them, so usually it shouldn't be a problem).
If your string representation of the datetime is in a format that is not supported by the built in convert function, you might need to do some extra work in the form of string manipulation to either change it into a supported format, or (in the harder case) separate the string representation to parts and then use datetimefromparts.
If you could provide the actual format you are using in your string representation of the datetime format I can probably edit this answer to show you exactly how to do it.
SELECT CONVERT(varchar(10),CAST('07/01/2018' AS DATE),23)
Result
2018-07-01
Not sure what you mean by, "date string is not in a straight format". Examples will help.
Have you tried parsing, instead of casting?
SELECT
TRY_PARSE(thedate AS datetime) as justParse
,TRY_PARSE(thedate AS datetime USING 'en-US') as parseUS
,TRY_PARSE(thedate AS datetime USING 'en-GB') as parseGB
,try_cast(thedate as date) as tryCast
FROM (values
('07/01/2018')
,('01/07/2018')
,('07 jan 2018')
,('jan 07 2018')
,('Monday, 7 January 2019')
)d(thedate)

Format DateTime without converting to String in SQL Server?

I have a view in SQL Server 2012 and there is a column of containing dates&times. I have been trying to convert the date column as '20/10/2018 18:00' format (no second) by using this feature and lots of approaches on Stackoverflow and other web sites:
FORMAT(StartDate, 'dd.mm.yyyy hh:mm')
However, as the data type of this column is Varchar (String) rather than DateTime, I encountered some problems in C# side and I want to perform this conversion on the database side without changing the data type of the generated format). Is there any way to achieve this?
SQL Server doesn't have a "date format" per se. The formatting of datetime fields is only performed when presenting the datetime to an output - that is, when converting it to a string.
There is a default format for presentation that is controlled by the server's collation setting. However, internally the date is stored as a numeric value (actual format varies by type, as datetime and datetime2 have different internal formats), and that value has no associated formatting.
You can store your date without seconds by using a smalldatetime field, or by manipulating the input data to trim off the seconds value. But, unless you store your date as a string, which is absolutely not recommended, you will not be able to save an output format different from the default collation-driven format in a datetime field.
I would migrate that column to a datetime (or some variant) if possible. Alternatively if that would affect too many things, you could make a computed column on the table which converts the string date you have to a datetime. That way the database doesn't have to care about the formatting at all; it just works with the proper DateTime data type.
If neither of those is an option, you can just pas the string to C# and use DateTime.TryParse() to convert it to a C# DateTime object.
In either case, it's preferable to work with the date as a DateTime up until the very last minute where you need to format it for display somewhere.

Access SQL Date Format

How can I retrieve a record based on a Date property? I'm trying:
WHERE Meetings.[MDate] = '16/12/2011'
which is the format I use but I get :
"Data type mismatch in criteria expression"
Problem solved: It should have been:
WHERE Meetings.[MDate] = 16/12/2011
No quotation marks.
For where clauses use
columnName = #mm/dd/yyyy#
You'll want to use the SQL date format: '#2011-12-16#'
Use the cast to DATETIME function, CDATE(), which will honour the machine's regional settings. That said, it still a good idea to use an unambiguous date format and the ISO 8601 format is a good one.
Also note that Access doesn't have a date data type: its sole temporal data type is DATETIME and, as its name suggests, always has a time element accurate to one second time granule, even if that time happens to be midnight. Therefore, it is a good idea to always include a time value to one second time granule in all DATETIME literals e.g.
WHERE Meetings.MDate = CDATE('2011-12-16 00:00:00');
Another advantage to the above is that the Access UI will not attempt to reformat the DATETIME literal because it is held as a string.