Datetime type conversion in SQL - 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())

Related

colon(:) and dot(.) as millisecond separator in datetime2

I have migrated a Sybase database to SQL server 2008.
The main application that using the database trying to set some of dateTime2 column with data like 1986-12-24 16:56:57:81000 which is giving this error:
Conversion failed when converting date and/or time from character string.
Running the same query using dot(.) instead of colon(:) as millisecond separator like 1986-12-24 16:56:57.81000 or limiting the milliseconds to 3 digits like 1986-12-24 16:56:57:810 will solve the problem.
NOTE:
1- I don't have access to the source of application to fix this issue and there are lots of table with the same problem.
2. Application connect to database using ODBC connection.
Is there any fast forwarding solution or should i write lots of triggers on all tables to fix it using the above solutions?
Thanks in advance
AS Gordon Linoff said
A trigger on the current table is not going to help because the type
conversion happens before the trigger is called. Think of how the
trigger works: the data is available in a "protorow".
But There is a simple answer!
Using SQL Server Native Client Connection instead of basic SQL Server ODBC connection handle everything.
Note:
1. As i used SQL Server 2008 version 10 of SQL server native client works fine but not the version 11 (it's for SQL Server 2012).
2. Use Regional Settings make some other conversion problem so don't use it if you don't need it.
Select REPLACE(getdate(), ':', '.')
But it will Give String Formate to datetime Which is not covert into DateTime formate
Why would you need triggers? You can use update to change the last ':' to '.':
update t
set col = stuff(col, 20, 1, '.');
You also mistakenly describe the column as datetime2. That uses an internal date/time format. Your column is clearly a string.
EDIT:
I think I misinterpreted the question (assuming the data is already in a table). Bring the data into staging tables and do the conversion in another step.
A trigger on the current table is not going to help because the type conversion happens before the trigger is called. Think of how the trigger works: the data is available in a "protorow".
You could get a trigger to work by creating views and building a trigger on a view, but that is even worse. Perhaps the simplest solution would be:
Change the name and data type of the column so it contains a string.
Add a computed column that converts the value to datetime2.

How do you convert SQL mm/dd/yy to mm/dd only?

How do you convert SQL mm/dd/yy datetime to mm/dd only? On Microsoft server.
Thanks all.
With dates and times it is an extremely common mistake to believe that what you see is what is stored. If the field is date, datetime, smalldatetime or datetime2 then what is stored are integers, not strings. So if the field is one of these, then:
convert(varchar(5),[date_field],1)
or
format([date_field],'MM/dd') -- mssql 2012 onward
If the information is a string already then left() will do the job.
Since you have specified an input format, the input must already be a string. Simply truncate with
cast(dateIn as char(5)).
You can use LEFT to just return the day and month:
SELECT LEFT('12/12/2000', 5)
I realize this isn't directly answering your question the way you asked it, but the best advice I can give is: Don't.
Instead, send back the field in its native datetime type. The database is not the place to be doing formatting. Instead, format the date in your application code.
For example, if you are calling SQL Server from a C#/.NET application, you could retrieve the value from a DataReader like this:
DateTime dt = (DateTime) reader["YourDateTime"];
Then you would format it as a string like this:
string s = dt.ToString("MM/dd");
This will ensure that the date is formatted correctly. If you are using a different language to call SQL Server, there are probably similar methods in that language.
One of the problems with the other approach mentioned (trunacating the string) is that the original value might not be formatted in mm/dd/yyyy to begin with. That all depends on the environment settings where the SQL Server is running. If you run the same code on an environment with dd/mm/yyyy settings, you would have unexpected results. This is avoided by using the native data type, the way I described.

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.

how to change datetime format for the whole database?

My application is based on format: mm/dd/yyyy
After deploying the database to the customer's side, it is based on: dd/mm/yyyy
I dont want to change all of my queries, so how can I change all the datetime format for the whole database?
It is MSSQL Server 2005
Thanks in advance.
If you wanted to you could write a class which would interoperate the date() function (which produces a timestamp) into a real date, which you could then insert into the database.
But you should be more specific, ie, what languages are you using to code in, if you are, etc?
You'll need to change the default language for the database and then change the default language for all of your logins. I have a blog that explains this:
Setting a standard date format
look at :Change default date time format on a single database in SQL Server
If question is related with SQL server only, it should be closed. If no, it should be moved to C# topic.

SQL Date Format Day and Month Mixup

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.