SQL Server Converting varchar to datetime - sql-server

I got a problem in SQL Server with converting a varchar to datetime. I would like to convert/update whole column [datelog] in table:
[dd.mm.yyyy hh:mm:ss]` to `[yyyy-mm-dd hh:mm:ss]

In SQL Server 2012+ you can use PARSE or TRY_PARSE to parse a text value according to a specific culture.
Assuming your text follows the German culture ('de-DE') you can parse it to datetime with :
select PARSE('24.11.2015 13:10:55' as datetime using 'de-DE')
eg:
select PARSE(datelog as datetime using 'de-DE')
The real solution though would be to use the correct field type, ie datetime. It's almost guaranteed that someone, somewhere will either enter text with the wrong format or try to convert the text using the wrong culture.
Date types on the other hand, have no format, they are simply binary values. Using them is faster, safer and easier.

Tricky solution,
DECLARE #inputDate AS VARCHAR(20)='21.11.2015 06:59:00' -- [dd.mm.yyyy hh:mm:ss]
SET #inputDate = REPLACE(#inputDate ,'.' ,'/')
SELECT CONVERT(VARCHAR(24) ,CONVERT(DATETIME ,#inputDate ,103) ,121) OutputDate -- [yyyy-mm-dd hh:mm:ss]
Still you need to change as per your table columns.

temp table with one column of type varchar
create table #temp3 (someDate varchar (30))
insert into #temp3 values ('23.03.1989 15:23:43')
using a combination of concat, substring and right
select concat
(
SUBSTRING(someDate,7,4),'-', SUBSTRING(someDate,4,2),'-',SUBSTRING(someDate,1,2), ' ', right(someDate, 8)
)
from #temp3
gives: 1989-03-23 15:23:43

Related

SSIS Convert m/dd/yyyy to yyyymmdd with inconsistencies

I'm loading many files into a SQL SERVER database. I have one flat file that has a Date Column coming in as string[DT_STR].
I have TWO "date fields" in my database. One is varchar, one is datetime.
Converting the datetime column is no issue, I just use Data Conversion/Derived Column if necessary. However, this varchar column is giving me trouble. Our database values for this column should be in yyyymmdd format. However, on this single file the format of the dates change.
Normally I'd do a SUBSTRING(...) expression here, but the difficulty is that the format of these dates change. some examples of values could be
08/16/2017
8/16/2017
08/6/2017
08/06/2017
10/6/2017
10/06/2017
This makes the challenge harder. I tried LEN([DATE]) == NUM_HERE ? do_THING : OTHER_CALC, but this approach failed because the length of 10/6/2017 is the same as 8/06/2017 which will give me the wrong result. Does anyone have a good workaround for this?
Perhaps a simple convert to date and then into the final format. If 2012+, use try_convert() to trap any bogus dates.
Example
Declare #YourTable Table ([SomeCol] varchar(50))
Insert Into #YourTable Values
('08/16/2017')
,('8/16/2017')
,('08/6/2017')
,('08/06/2017')
,('10/6/2017')
,('10/06/2017')
Select *
,Formatted = convert(varchar(8),convert(Date,SomeCol),112)
from #YourTable
Returns
SomeCol Formatted
08/16/2017 20170816
8/16/2017 20170816
08/6/2017 20170806
08/06/2017 20170806
10/6/2017 20171006
10/06/2017 20171006
Convert the varchar data to datetime and convert that to a formatted string
SELECT CONVERT(varchar,(CONVERT(datetime, '8/6/2017')),112)

SQL Server: convert StartDATE 20140804 Nvarchar to Datetime2

I'm using SQL Server 2008 and I did an import from a flat file. I couldn't import the datetime column properly so I specified it temporarily as a nvarchar(50).
Now I want to convert it to datetime2 format. However when doing so, I get the error
Conversion failed when converting date and/or time from character string.
The data that is currently in my nvarchar(50) column looks like this:
20140804
And I need to convert it to:
2014-08-04 00:00:00.0000000.
Note that I do not only want to convert one date, but all StartDATE values in my table and insert them to another table
Any help is appreciated.
Insert into targettab(datecol,<othercols....>)
select cast(datefield as datetime2),<othercols...> from sourcetab
You can use cast function
you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare #i int
select #i = 20100101
select CONVERT (datetime,convert(char(8),#i))
SELECT convert(varchar, StartDATE , 113) from ur table

Which settings provide SQL Server default datetime format?

Say, I have a table like this :
Table name "DateTimeFormatCheck" >
I used below query to insert :
Insert into [dbo].[DateTimeFormatCheck] ([DateTimeCheck]) values('11/19/2014 1:29 PM')
It inserted date like 2014-11-19 13:29:00.000 , but my insertion format(M/d/yyyy h:m tt) is not same as inserted date.
Now i want to know How SQL Server detect my string date format that i have provided ? and Why it always provide this format yyyy-MM-dd HH:mm:ss after insertion?
Thanks
Don't do that! Don't use strings instead of dates and don't use a culture-specific date or datetime format, it's a recipe for disaster.
SQL Server doesn't have a "date format", just formats it uses to convert dates to and from strings. One of them is the default, controlled by the server's collation. You can neither assume nor should you depend on a specific collation, so you should avoid conversions whenever possible. Moreover, passing a string value can prevent SQL Server from using indexes on date columns because it would have to convert the string to the underlying column type.
It's far easier and safer to pass dates as date-typed variables or parameters. You avoid the entire conversion mess this way, to and from and avoid SQL injection attacks.
There's no reason to pass strings instead of dates to the server. All SQL Server clients (including ADO.NET) allow you to execute parameterized queries. ORMs like NHibernate and Entity Framework also generate parameterized queries for date-typed columns.
Whenever you need to create a string literal, use one of the invariant formats like 20140913 or 2012-11-07T18:26:20
You can read more about it at Writing International T-SQL Statements
The format of sqlserver is yyyy-mm-dd, but you can define your input by execute the command
set dateformat dmy -- to accept dmy format
set dateformat mdy
select cast( '11-9-2014' as date)
set dateformat dmy
select cast( '11-9-2014' as date)
updated
Ideally you can not try to change format, you can validate your data and then insert.
Whenever we insert into datetime datatype, sqlserver will implicitly try to convert into mmddyyy hhmmss format. so if you given date as 19/11/2014 , it convert into 11/19/2014 means 19th nov 2014.
But if you give more than 12 in the middle portion, it will not convert implicitly and throw the error of conversion.
Other than mmddyyyy format, you must use to cast or convert function explicitly to allow the data insert or update.
Before the casting you can use ISDATE or TRY_PRASE or PARSE function in sqlserver, will check to conversion possible or not.
you can create a function or just add line as
declare #dt varchar(50) = '19-11-2014 10:10:41'
declare #dTable table ( datecolumn datetime)
INSERT into #dTable values (
case
when isdate(CONVERT( varchar(50), #dt)) = 1 then CONVERT( varchar(50), #dt) --'19-11-2014 10:10:41'
when isdate(CONVERT( varchar(50), #dt, 103) ) = 1 then CONVERT( datetime, #dt , 103 ) --'19-11-2014 10:10:41'
when isdate(CONVERT( varchar(50), #dt, 102) ) = 1 then CONVERT( datetime, #dt , 102 ) --'19-11-2014 10:10:41'
--when --give other format as above given and if not set in any dateformat , then simply return null
else
null
end )
select * from #dTable

Converting NVARCHAR(255) to DATE

I'm trying to transfer some old SQL Server data using Excel into SQL Server. It seems that Import/Export Data application automatically sets most data columns to NVARCHAR(255). Problem I have, is one of my columns is supposed to be a DATE type, but all data in it looks like this 18.08.2000 14:48:15.
So, when I try to use this query:
SELECT CONVERT(Date, DATE_TIME, 113)
FROM someTable
I get this error:
Msg 9807, Level 16, State 0, Line 1
The input character string does not follow style 113, either change the input character string or use a different style.
None of the [styles] from CAST and CONVERT (Transact-SQL) are working in my case.
Any advise or help is greatly appreciated.
SOLVED:
UPDATE myTable
SET columnName = CONVERT(NVARCHAR(255),CONVERT(SMALLDATETIME, columnName,105))
ALTER TABLE myTable
ALTER COLUMN columnName SMALLDATETIME
So, if it will ever become useful to anyone, this is the exact code that changes datatype NVARCHAR to DATETIME:
UPDATE myTable
SET columnName = CONVERT(NVARCHAR(255),CONVERT(SMALLDATETIME, columnName,105))
ALTER TABLE myTable
ALTER COLUMN columnName SMALLDATETIME
As far as I can tell - style no. 103 (British/French) should work - no?
DECLARE #input NVARCHAR(255)
SET #input = '18.08.2000 14:48:15'
SELECT CONVERT(DATETIME, #input, 103)
Gives me the output of:
2000-08-18 14:48:15.000
which seems pretty reasonable, no??
If you are using SQL Server 2012, try:
PARSE(Date AS datetime USING 'en-GB')
Or if that doesn't work, try:
PARSE(Date AS datetime USING 'Et-EE')
The Estonian culture specifically uses '.' as a date separator (d.MM.yyyy H:mm:ss) so it should work.
(Both seem to work fine on SQL Fiddle)

Convert varchar column to smalldatetime

I have a table with 800+ records. In this table I have a column named 'Data' of varchar(10) datatype which contains dates in dd.MM.yyyy format.I want to convert it to smalldatetime.
I've tried converting it using Enterprise Management Studio Express, but I receive this error:
The conversion of char data type to smalldatetime data type resulted in an out-of-range smalldatetime value.
How can I convert it?
I think you'll need to do a little string manipulation to get this to work as I think SQL is expecting 'MM.dd.yyyy'. So, update your table to flip-flop the month and day first, then the conversion should go through.
update YourTable
set Data = SUBSTRING(Data,4,3) + LEFT(Data,3) + RIGHT(Data,4)
You can use:
SELECT ID, CAST(VarcharCol As SmallDateTime) as DateTimeCol From Test1
This will return a table with varcharcol values as smalldatetime
Then update the content of varcharcol with the new values.
If you don't want implicit conversion to smalldatetime, you should use CONVERT and the argument style.
dd.MM.yyyy format correspond to style 104.
For example :
SELECT CONVERT(smalldatetime, '31.12.2018', 104) AS "Result"
Result
------
2018-12-31 00:00:00

Resources