When supplying dates to a stored procedure via a parameter I'm a little confused over which format to use for the dates. My original VBA syntax used the ADO Connection object to execute the stored procedure:
Set SentDetailRS = Me.ADOConnectionToIntegrity.Execute("dbo.s_SelectAggregatedSentDetailList '" & fCSQLDate(EffectiveDate) & "'", , adCmdText)
This works fine for me using the date syntax yyyy-mm-dd but when another user executes the code they recieve the error: 13 'Type Mismatch'.
After some experimentation I found that supplying the date in the format dd/mm/yyyy fixes this error for the user but now gives me the error!
Executing the stored procedure using a command object with parameters works regardless of the format of the date (I assume ADO is taking care of the formatting behind the scenes). I thought that using the format yyyy-mm-dd would work universally with SQL Server?
I'm also perplexed as to why this problem appears to be user specific? I noticed that my default language on SQL Server is 'English' whereas the other user's default language is 'British English', could that cause the problem?
I'm using ADO 2.8 with Access 2003 and SQL Server 2000, SQL Server login is via Windows integrated security.
Be careful, and do not believe that ADO is taking care of the problem. Universal SQL date format is 'YYYYMMDD', while both SQL and ACCESS are influenced by the regional settings of the machine in the way they display dates and convert them in character strings.
Do not forget that Date separator is # in Access, while it is ' in SQL
My best advice will be to systematically convert your Access #MM-DD-YYYY# (or similar) into 'YYYYMMDD' before sending the instruction to your server. You could build a small function such as:
Public function SQLdateFormat(x_date) as string
SQLDateFormat = _
trim(str(datePart("yyyy",x_date))) & _
right(str(datePart("m",date)),2) & _
right(str(datePart("d",date)),2)
''be carefull, you might get something like '2008 9 3'
SQLDateFormat = replace(functionSQLDateFormat," ","0")
'' you will have the expected '20080903'
End function
If you do not programmatically build your INSERT/UPDATE string before sending it to the server, I will then advise you to turn the regional settings of all the machines to the regional settings of the machine hosting SQL. You might also have to check if there is a specific date format on your SQL server (I am not sure). Personnaly, I solved this kind of localisation problems (it also happens when coma is used as a decimal separator in French) or SQL specific characters problems (when quotes or double quotes are in a string) by retreating the SQL instructions before sending them to the server.
I would guess that fCSQLDate function is culture-specific - i.e. it will parse the date based on the user's locale settings. That's why you see the problem.
Anyway, using queries with concatenated strings is always a bad idea (injection attacks). You are better off if you use parameters.
Access uses # as date field delimiter. The format should be #mm/dd/yyyy# probably the #mm-dd-yyyy# will also work fine.
Sorry I don't know mysql, but with oracle I would always explicity state the format that I was expecting the format to be in, eg: 'DD-MM-YYYY', to avoid (regional) date format problems
Why not use the format
dd mmm yyyy
There is only one way it can be interpreted.
You can use the Date() function to return a universal date based on the machine date and time settings. The region settings on the machine will determine how it it formatted on the client end. If you leave the field as strictle a DateTime field then the cleint region settings can format the date.
Going into the server, using the Date() function should aslo work (returning a universal date value).
Also, use a command object and parameters in your query when you pass them to avoid SQL injection attacks on string fields.
Related
My local SQL Server 2016 setup at work decided not to accept the YMD date format after going through a reinstall. For example, the following query, that was and still is accepted in my coworkers' setups:
SELECT "id"
FROM test.dbo.tabEmp
WHERE "DateAdmission" <= '2021-12-31' AND "DateAdmission">= '2021-12-30' `
When I try to run it I see this:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
however, if i rewrite the dates as 2021-31-12 and 2021-12-30, in the YYYY-DD-MM format, they are accepted.
I can't really convert or format it since the sql queries in our system are numerous and done so in a way that it would be nearly impossible to. Is there something that can be done? I tried changing windows' Date format but to no avail.
For the datetime and smalldatetime data types the format yyyy-MM-dd is not unambiguous (note that it is for the newer date and time data types). If you are not American, the date will very likely be interpreted as yyyy-dd-MM, and as there are not 31 months in the year you get an error.
For SQL Server, the formats that are unambiguous regardless of data type and language setting are yyyyMMdd and yyyy-MM-ddThh:mm:ss.nnnnnnn; ideally if you are using string literals use one of those formats as you can never get an error (unless you legitimately have an invalid date).
Otherwise you can explicitly CONVERT your value with a style code:
SELECT CONVERT(datetime, '2021-12-31', 126);
It seems that your new DB instance picked up a new language after the reinstallation.
The current language setting determines the language used on all system messages, as well as the date/time formats to use.
The date format setting affects the interpretation of character strings as they are converted
to date values for storage in the database. It does not affect the display of date data type values
that are stored in the database or the storage format.
You can run the following statement to return the language currently being used:
SELECT ##LANGUAGE;
This will tell us what the current language is and the date format (as well as a few other things):
DBCC USEROPTIONS;
Date format is modifiable via the following statements:
SET LANGUAGE us_english;
SET DATEFORMAT YMD;
Here is a good article on the subject: How to Change the Current Date Format in SQL Server (T-SQL)
It is also possible to modify SQL Server instance default language globally, once and for all: How to change default language for SQL Server?
Have an instance of SQL Server 2012 that appears to correctly interpret string literal dates whose formats are not listed in the docs (though note these docs are for SQL Server 2017).
Eg. I have a TSV with a column of dates of the format %d-%b-%y (see https://devhints.io/datetime#date-1) which looks like "25-FEB-93". However, this throws type errors when trying to copy the data into the SQL Server table (via mssql-tools bcp binary). Yet, when testing on another table in SQL Server, I can do something like...
select top 10 * from account where BIRTHDATE > '25-FEB-93'
without any errors. All this, even though the given format is not listed in the docs for acceptable date formats and it apparently also can't be used as a castable string literal when writing in new records. Can anyone explain what is going on here?
the given format is not listed in the docs for acceptable date formats
That means it's not supported, and does not have documented behavior. There's lots of strings that under certain regional settings will convert due to quirks in the parsing implementation.
It's a performance-critical code path, and so the string formats are not rigorously validated on conversion. You're expected to ensure that the strings are in a supported format.
So you may need to load the column as a varchar(n) and then convert it. eg
declare #v varchar(200) = '25-FEB-93'
select convert(datetime,replace(#v,'-',' '),6)
Per the docs format 6 is dd mon YY, but note that this conversion "works" without replacing the - with , but that's an example of the behavior you observed.
Warning: Classic ASP Ahead. :)
I'm working on a legacy Classic ASP application and I'm running into an oddity with an ADODB.Recordset object.
I have a SQL2012 database table containing a particular field. Let's call it AnnoyingField. Its datatype in SQL is 'date'.
The ASP opens an ADODB.Recordset with a SELECT on the table to collect the fields, then does some looping to do its work:
For each Field in rs.Fields
typeid = rs(Field.Name).Type
'do stuff based on type
For some reason, the Type for AnnoyingField is coming back as 202 (nvarchar) rather than one of the expected types for date (133 or even 7). This is causing some issues further in the code.
I tested with another field of 'datetime' type and the Recordset code returned the expected Type for a datetime field.. 135.
Anyone have an idea why the 'date' fields are returning as an nvarchar?
Changing the database fields from date to datetime in this case might not be possible, even though it might be the logical path to take to get expected data.
Date fields are newer than your version of ADODB. So it doesn't understand what it's getting.
You may be able to cheer it up by using
select convert(datetime, AnnoyingField) from CrazyFuturisticTable
You may also get the correct result if you upgrade your ADODB version to 2.8 and/or connect using the SQL Native Client. Obviously, I haven't tried this, because I live in 2014.
If you keep it a little simpler, cut ADO out of the picture and use isdate and "convert date" and vartype.
For each Field in rs.Fields
Field=rs(Field.Name)
if isdate(Field) then Field=cdate(Field) ' just in case
typeid = VarType(Field)
'do stuff based on type
Vartype
http://www.w3schools.com/vbscript/func_vartype.asp
ADO .type can report more "types"
http://www.w3schools.com/ado/prop_para_type.asp
But I think what vartype can offer should help people in 95% of cases.
Word of warning with cdate, depending on what the server locale is set too or your Session.LCID (in your code) is set will determine what format the date will be formatted to. Shouldn't be a problem for most people but obviously test to see if you get the expected result.
I am using Classic ASP / VBScript and have found that for SQL2012 using SQL Native driver ("Provider=SQLNCLI11"), and the ADO module provided by Windows (presumably Vista or newer [mine is Windows Servr2012 R2 - the version [MyDbConn.version] shows as 6.3) this now works again.
I had been looking for / expecting the Field.Type to be adDate [7], but am actually getting adDBDate [133]
We have recently moved some data from an SQL Database instance to another one in another location.
I seemed to have noticed that there are some facets of our old database instance where the date is passed as String to the SQL server and SQL server is able to parse it properly. For example, the application would simply pass a string value of "15/01/2010" and the database would immediately recognize it as 5th of January 2010. Is there a setting in SQL server which I need to turn on or modify cause right now, when I passed the same string value, what happens is that an error is being generated cause it cannot understand the string value passed as a date.
Thanks for your inputs.
try
SET DATEFORMAT dmy
but you should only use 'safe' formats when using strings
same formats are YYYYMMDD and yyyy-mm-ddThh:mi:ss.mmm (no spaces). It doesn't matter with these 2 formats what your language settings are
Take a look here: Setting a standard DateFormat for SQL Server
If you need to convert output use cast or convert
select convert(varchar(30),getdate(),101)
03/08/2010
select convert(varchar(30),getdate(),101) +' '
+ convert(varchar(30),getdate(),108)
03/08/2010 15:21:32
I have a problem.
I have an application in C# with SQL SERVER 2005 as backend.
The problem is in fetching the correct record based on the date.
The frontend code is
if (string.IsNullOrEmpty(txtFromDate.Text))
SelectCmd.Parameters[0].Value = DBNull.Value;
else
SelectCmd.Parameters[0].Value = txtFromDate.Text;
Now if I run usp_NewGetUserDetail '03/04/2010' in the query analyser, I am able to get the correct record.
So I am preety confident that my SP is correct(I have tested with many variations).
But if the same value is passed from front end code(SelectCmd.Parameters[0].Value = "03/04/2010";), I am getting some unexpected record. By that I mean , the records which are not in the date range.
I guess that there is some mismatch in date format of backend and frontend.
Kindly let me know if I missed out some information that I need to provide for solving this
Please help.
Dealing with dates on SQL Server is a tricky business, since most formats are language- and locale-dependent. As Adam already mention - you should try to avoid dealing with dates as strings - it does get messy, and using DateTime (both in .NET and in T-SQL) is much safer and easier.
But if you must use strings, then be aware of these points: a date like 02/05/2010 will be interpreted as Feb 5, 2010 in some places, or as May 2, 2010 in others. So whatever you're doing - you'll always run into someone who has a different setting and gets different results.
The way to do here is to use the ISO-8601 format which is independent of all locale and language settings and just always works.
So for your dates, always use the YYYYMMDD format - first of all, it always works, and second of all, with that format, you get a "natural" sort behavior - sorted by Year, then Month, then Day.
There's no need to pass the date as a string, nor should you. Set the value of the parameters to a DateTime object that represents the date you want, not the string representation of it.
Try something like this:
DateTime fromDate;
if (DateTime.TryParse(txtFromDate.Text, out fromDate))
{
SelectCmd.Parameters[0].Value = fromDate
}
else
{
SelectCmd.Parameters[0].Value = DBNull.Value;
}