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
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.
I'm working on a project running on an existing database. The problem is that datetime columns are inserted using a wrong format in SQL Server. The server uses datetime as Y-m-d and data is being saved as Y-d-m.
I've made some tests, and when saving to MariaDB datetime is saved properly.
There are custom fields for updated_at and created_at, so they are declared on the model.
In the model
class NotaFaturamento extends Model
{
const CREATED_AT = 'DT_CADASTRO';
const UPDATED_AT = 'DT_ATUALIZACAO';
This is the QueryLog print after saving data. As you can see in the query log, datetime format is correctly parsed to SQL Server.
Querylog
On Config\app.php
'timezone' => 'America/Sao_Paulo',
'locale' => 'pt-BR',
Is this something that needs to be configured on SQLServer? I've searched a lot about this, but most of the responses are regarding SQL Server separators.
I also declared protected $dateFormat = 'Y-m-j h:i:s:000A'; on the model but the same problem happens. The issue is also present when storing Carbon objects.
Regards.
EDIT
As pointed out by Dan, the issue could be the DATEFORMAT on the SQL Server being used as DMY. Also, as pointed this issue and answered by #dns_nx, there is a workaround to manually change dateformat for saving on SQL Server.
I've added to my model
public function getDateFormat()
{
return 'Y-d-m H:i:s.v';
}
And any other date attributes on the model should be declared as being date:
protected $dates = ['DT_EMISSAO', 'DT_COMPETENCIA'];
I don't think this is the proper way to solve the issue, but it does work. And you could create another basemodel as mentioned by #dns_nx.
Regards
I can't speak to Laravel/Eloquent specifically but a parameterized query with a strongly-typed datetime parameter will save the value properly. Since the value is not being saved correctly, it is because:
1) The actual parameter value provided for a datetime parameter type is wrong
2) The parameter type is (n)varchar with the value passed as a string that doesn't conform to ISO 8601 format
3) The parameter is passed as a string literal that doesn't conform to ISO 8601 format
For troubleshooting, run a SQL Trace (Extended Events or Profiler) on your dev database instance including batch_completed and rpc_completed events to capture the actual SQL queries. This will identify which of the above causes is the culprit. The rpc_completed will include both the parameter type and value. Be aware that with a datetime parameter type, the trace will always display the datetime value in YYYY-MM-DD hh:mm:ss.fff format, which is just a rendering of the actual binary value passed.
If the parameter type is (n)varchar, the non-ISO 8601 datetime string '2018-10-06 09:07:07.222' will be parsed by SQL Server using the current session DATEFORMAT setting. The default DATEFORMAT for a Portuguese language login is DMY but can be overridden by an explict SET DATEFORMAT command previously executed on the same session. With DATEFORMAT DMY and the string value '2018-10-06 09:07:07.222', the month and day portion will be parsed as month 6 day 10. Datetime literals are similarly parsed.
A quick search turned up this issue. Consequently, if you can't coerce a strongly-typed datetime to be passed by the application, a workaround may be to use datetime2(3) instead of datetime. SQL Server will parse datetime2 string '2018-10-06 09:07:07.222' as YYYY-MM-DD hh:mm:ss.fff regardless of the session DATEFORMAT setting. I recommend datetime2 for new development since it won't round the fraction seconds to 1/300 units and store greater precision values in less space.
MS Excel 2010 64-bit
Windows 7 Pro 64-bit on the local machine
SQL Server 2012
I often call stored procedures in SQL Server to return data to Excel for analysis in PivotTables. I pass parameters to the sp's using the following syntax in Microsoft Query's SQL Editor:
{Call dbo.MySP(?,?,?,)}
Where dbo.MySP is an SP that takes three parameters. When I return the output from the query to Excel I get to select which cells to refer to to get the parameter values.
Yesterday I wrote an SP that takes 3 arguments: a date, another date and a text string delimited by commas. The SP has them declared as two DATETIMES and an NVARCHAR(4000). As usual, I convert the dates in Excel to text strings in the form yyyy-mm-dd to pass them, but the text string is just a string of characters with individual values delimited by a pipe (|).
When I attempt to select the cell containing a text string less than 255 characters all is well. If I go over 255 I get an error from Excel complaining:
Bad parameter type. Microsoft Excel was expecting a different kind of
value that was was provided.
Changing the delimiter has no impact.
Is that a hard limit on the length a parameter passed from Excel can handle?
Is there a workaround of any sort?
Note that is is clearly an Excel limitation, running the same query with any length parameter works fine in SSMS.
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.