SQL Date Format Day and Month Mixup - sql

It seems this question is asked a lot, but none of the answers have given me results. I'm pulling my hair out here ... so hopefully someone has an answer.
I have a production server running SQL Server 2005. I backed up the db and restored it on my laptop's SQL Server Express instance. Now date queries are seriously affected. In the prod. server they are all stored as "4/13/2011 12:00:00 AM" format, but on my laptop they are showing as "2011-04-14 00:00:00.000". When I do a query trying to find entries on "4/14/2011" my laptop gives me the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value". Edit: This exact query runs fine on the production SQL server. (I'm using SSMS to run queries ... not an application/code)
I made sure my laptop's Windows regional settings are the same as the server (English(United States)) and everything on the Region and Language control panel is the exact same.
Finally I ran the following two queries:
select name ,alias, dateformat
from syslanguages
where langid =
(select value from master..sysconfigures
where comment = 'default language')
select ##language
Which gave the result of "*us_english, English, mdy*" ..... and "British" respectively. Where is this British coming from?! Now when I run this command before my query (in the management studio)
SET DATEFORMAT mdy
Then everything works perfectly! But in the syslanguages query it seems to already be mdy format. I'm not about to rewrite my application with "SET DATEFORMAT" all over the place - so hopefully someone has a clue. Maybe my SQL Express installation is buggared and I have to reinstall it?
I'm going to keep tinkering to hopefully get this to work.

It is the language settings of the login that you need to change.
You can do it through SSMS -> Security -> Logins -> YourLogin -> Properties -> Default Language
Or through TSQL
ALTER LOGIN [YourLogin] WITH DEFAULT_LANGUAGE=[us_english]

If you specify things in dd-mmm-yyyy format, or better still, use DateTime parameters (rather than varchar input), you won't have a problem.
Try changing the default language to us-english, using the following:
EXEC sp_configure 'default language', 1033
RECONFIGURE
If that doesn't work, you could try language code 0.

Are you passing dates as string literals - or concatenating strings to build up the sql in your application?
If you are doing this, consider using parameters for the dateTime data types. Or at least escape them using the ODBC escape clause and format them as in { ts'yyyy-mm-ddhh:mm:ss[.fff] '} such as: { ts'1998-09-24 10:02:20' }.
It is most probably your application not passing the datetime properly.

Related

SQL Runner (Google Looker) change date format in query

This topic has been covered several times but I can't find a solution that applies to SQL Runner, which is the custom query portion of Google's Looker platform.
I am attempting to reformat a datetime SELECT statement from yyyy-mm-dd to mm-dd-yyyy.
Currently what I have is:
SELECT
CAST(shift.datetime AS DATE)
FROM table.a
This gives me the yyyy-mm-dd result but so far my efforts to CONVERT have been fruitless. It does not appear that SQL Runner supports the CONVERT command or I am utilizing it incorrectly.
Any thoughts on this one?
I believe sql runner is just gives us a way to directly access the db and it will not change any sql query while communicating with the db directly as long as the timezone of both explore as well as db matches.
Maybe something like this should work for your case
https://sql.tutorialink.com/convert-yyyymmdd-to-mm-dd-yyyy-in-snowflake/
lmk if the above works for your or not!

Datetime type conversion in SQL

I am getting data from some external datasource and need to store in SQL server table. But one filed in it is Datetime. But I am getting that datetime field as Varchar format, and now in my SQL table I need to save it as DateTime datatype.
CONVERT(DATETIME,[Date_time],03)
-- This code work in my Development Environment but not in Production.
CONVERT(DATETIME,[Date_time],120)
-- This code work in my Production but not in development.
This make my life difficult to transfer code from development to Production since I have to make changes in tested code.
Please note that I am using SQL server 2008 R2.
Is there anyway that I can make code similar? I cannot change the culture and language on both server since many other applications are deployed there and it might break existing application in both server.
You can try to use a SET statement to override the date format, something like this:
SET DATEFORMAT mdy;
SELECT CONVERT(DATETIME, [Date_Time], 120);
As long as you include this code in your stored procedure/query on both environments, this should be fine. You may want to read up about this on MSDN.
A workaround for your problem would be to provide a feature that calculates (or defines) the correct style for each environment. This simplest option would be a user-defined function.
CREATE FUNCTION [dbo].[fnCustomDateStyle]()
RETURN int AS
BEGIN
RETURN 3 # Or 120, in the other environment
END
Which can be used in every environment thus:
CONVERT(DATETIME, [Date_Time], fnCustomDateStyle())

Select GetDate() via VB.net different then Select GetDate() via SSMS

When I Use the below code:
Dim cmd As New OdbcCommand("SELECT GETDATE()", oConn)
retVal = cmd.ExecuteScalar()
The resulting output is:
8/1/2013 10:10:39 AM
When I run the exact same query directly in Management Studio I get:
2013-08-01 10:10:39.317
When I check my computer settings versus the SQL Server settings they match.
Anyone know what I need to do to ensure it matches?
Specifically I am talking about the Date format difference.
If you want the date output with a specific string format, then you can use CONVERT() with a style number. For example:
SELECT CONVERT(CHAR(20), GETDATE(), 22),
CONVERT(CHAR(23), GETDATE(), 21);
Results:
-------------------- -----------------------
08/01/13 10:53:54 AM 2013-08-01 10:53:54.943
However, if you are using the date for things other than direct display, only apply that formatting when you are displaying it. For all other purposes it should remain a datetime type and should not be converted to a string.
As for the differences in the actual time value, it's not clear what problem you're talking about, but I suspect you simply ran these queries half an hour apart. If those were run at or around the same time, it looks like the server is half an hour fast - maybe it's in a different time zone or maybe it's just a lot of drift or someone not bothering to use a time service. Your application should never use the time / time zone of the client, especially if it's distributed - always use the time on the server.
Dates have no format. Format comes into play only when you convert dates to a string. The forma used depends on who does the conversion: the server or the client?
Your VB.NET query returns a date from the server and converts it to a string when you write it to the console, a form or whatever. VB.NET uses your programm's CurrentCulture, whose defaults come from the current user's regional settings.
When you display data in SSMS, an ISO format is used so there is no ambiguity when you edit the data.
When you compare date and string values in a query, either explicitly by converting a date to a string or implicitly because you just typed MyDate = '13/1/2013, a conversion is made using the column's collation. Collations are inheritted so the column's collation is the same as the database's collation.
Try this:
net time \\SERVER_NAME
Note: Obviously SERVER_NAME is the name of your SQL Server machine.
Do you see a 30 minute difference in the result of that call?
I looked deeper into the code and found that some enterprising fellow had added code to a line of SQL later in the process which forces DMY format on that query.
so the code in the VB is returning the proper Date on the app machine. Which means that there must be a difference between my computer and the app machine.
Another coder ran into the same issue and so there solution was to add the below code to the SQL that was pulling from the DB.
SET DATEFORMAT dmy
This forces the SQL to use DMY format... I removed this code Compiled and ran the EXE from the server machine and my issue dried up!
Thanks for everyone's help.

Configure date format used by FoxPro database

The problem in short: The same database returns dates in a different format on different servers and I'm having trouble to configure it to correct date format.
I have the following situation:
A PHP-based web application that gets it's data from Microsoft FoxPro 9 databases.
The database connection is made with OleDB. In PHP this utilises ADODB through COM objects:
$this->connection = new COM("ADODB.Connection");
$this->connection->Open($this->connectionString);
The connection string looks like this:
Provider=VFPOLEDB.1; Mode=Share Deny None; Window Handle=0;
Locale Identifier=1033; Prompt=4; Extended Properties=0;
User ID=; Password=; Mask Password=False; Cache Authentication=False;
Encrypt Password=False; OLE DB Services=0; Collating Sequence=MACHINE; DSN=;
DELETED=True; ENGINEBEHAVIOR=80; TABLEVALIDATE=0;
Data Source=\\path\to\file.DBC
The program is deployed on different servers throughout the world, running on different versions of Windows Server (2003-2008 R2). Query's are executed the following way:
$this->connection->Execute($query);
This returns a resultset with all values in plaintext. This is where the problem arises. The databases don't use the same formatting for dates, which makes it difficult to process the dates later on in PHP.
So far, the app can cope with the US format: mm/dd/yyyy and the dutch format: dd-mm-yyyy. The program just assumes that when the date contains slashes the US format is used and when there are hyphens the d-m-y format is used.
This has been going fine for a long time, but now we recently deployed the program to a server in Brazil, which returns dates in the Brazilian format dd/mm/yyyy. The program obviously now confuses this with the US format.
I've been trying to get the database to report in a different date format (US) to no avail.
On two different dev-environments, changing the Regional settings of windows to a different country immediately alters the date-format the database uses. These dev-environments are all Windows 7 systems.
However, this won't work on the servers with Windows Server. I have changed around all of the Regional settings (Formats, Location and System locale) on multiple servers without any results. Even after rebooting or reïnstalling FoxPro with the correct regional settings. The databases keep reporting in the date-format they seem stuck in.
Does anybody know how I can change the date-format used by FoxPro on a Windows Server environment?
Other options I have explored include putting regional information into the DSN, but couldn't I find any possible way. Also the FoxPro statement SET DATE TO ..... is not accepted through OleDB.
Altering the application to understand the Brazilian format or to add a bunch of if-else statements doesn't seem like a feasible solution.
The FoxPro date type is date-format-insensitive. That is, if you simply return the value as a date (datetime) rather than converting to character, you shouldn't have any problems.
Wrap your FoxPro date field the DTOC function, with the second optional parameter. This will return a standard YYYY-MM-DD style date, regardless of regional setting.
SELECT DTOC(dDate) as dDate FROM Alias
If that's not feasible, you'll need to investigate the functions to explicitly set a locale in FoxPro, such as the intuitively named SYS(3005).
And if even that's not feasible, you'll need to resort to requiring servers in foreign countries to have their regional settings standardized at the OS level.
Maybe be explicit in your query and handle reconstructing the date within the web application. So if you have a date-type field in VFP called MyDate then do:
select x, y, z, day(MyDate) as daynum, month(MyDate) as monthnum, ;
year(MyDate) as yearnum from mytable
OK, so it's more work on the other reconstructing a date from that but at least it should be location-agnostic.

Accepted date format changed overnight

Since yesterday I started encountering errors related to date formats in SQL Server 2008.
Up until yesterday the following used to work.
EXEC MyStoredProc '2010-03-15 00:00:00.000'
Since yesterday I started getting out of range errors. After investigating I discovered the date as above is now being interpreted as "the 3rd of the 15th month" which will cause a out of range error.
I have been able to fix this using the following format with the "T".
EXEC MyStoredProc '2010-03-15T00:00:00.000'
By using this format its working fine. Basically all I'm trying to find out is if there is some Hotfix or patch that could have caused this, as all my queries using the first mentioned formats have been working for months.
Also this is not a setting that was changed by someone in the company as this is occurring on all SQL 2005/2008 servers
The language setting of the session can change this.
--This works
set language english
select cast('2010-03-15 00:00:00.000' as datetime)
--This doesn't
set language french
select cast('2010-03-15 00:00:00.000' as datetime)
With the T in between, it always works. If you want a space, then leave out the hyphens.
--This works
set language english
select cast('2010-03-15T00:00:00.000' as datetime)
--This works
set language french
select cast('2010-03-15T00:00:00.000' as datetime)
--This works
set language english
select cast('20100315 00:00:00.000' as datetime)
--This works
set language french
select cast('20100315 00:00:00.000' as datetime)
So my guess is that your app has changed... or some setting on your client computer.
To avoid these kind of problems you should always specify your date format. For your purposes you should use:
SET DATEFORMAT ymd;
See this MSDN page - note the comment that
ydm is not supported for date, datetime2 and datetimeoffset data types
so you might have to use a different format if you're using one of those data types.
It sounds like you've got a mixture of date styles - yyyy/MM/dd vs yyyy/dd/MM - which seem to be reverse UK and US style dates.
If all servers are showing the same behaviour it could be that just the machine executing the code has changed rather than the other machines/SQL servers in the network.
Double check that the date format or indeed culture settings are what you expect them to be on that machine. Assuming they weren't you might be able to find out what changes to the machine were made over the weekend from the event logs or Windows Update history.
Collation can effect dates, as well as the language.
To check what default language a server has installed, use the following SQL command:
sp_configure 'default language'
If the resulting value is 0, the default language U.S. English. If the result is not 0, run the following SQL command to find the installed default language setting and date format used:
select name ,alias, dateformat
from syslanguages
where langid =
(select value from master..sysconfigures
where comment = 'default language')
NOW as to the system updates updates, those were in 2007 to adjust to the DST changes mandated back then.
Machine specific: you CAN set the clock on a specific machine to NOT adjust for DST - check that setting per machine (Windows it is on Control Panel/Date and Time under XP for instance).
IF you choose to use the dashes, you may have issues in dates. If you take out the dashes, SQL Server will never misinterpret the data:
EXEC MyStoredProc '2010-03-15 00:00:00.000'
this is likely getting a time with a negative hour offset, which is in this case invalid.(just a guess)
vs
EXEC MyStoredProc '20100315 00:00:00.000'
Note that the T in there is the ISO8601 format, and thus the dashes are allowed.
Ok I just read a post over at Simons SQL Blog (http://cli.gs/hqaR4) about this specific issue. So one solution to this problem is to Use the new DATETIME2 datatype as it understands languages that doesn't use MDY dates