converting a varchar to datetime in sql server - sql-server

I have a varchar 20130909132512 and I would like to convert it into just a date 2013-09-09
I keep getting an error when trying
select convert(datetime,'20130909132512',105)
and I am trying to avoid using
select convert(datetime,SUBSTRING('20130909132512',0,8),105)
if possible. Any ideas on how I can do this?

You could transform your varchar to 20130909 13:25:12 using STUFF
Declare #a Varchar(20)
Select #a = '20130909132512'
select convert(datetime,
STUFF(STUFF(STUFF(#a,13,0,':'),11,0,':'),9,0,' ')
,105)

Whether you use bummi's STUFF method or continue using SUBSTRING, you're going to have to pre-format the string no matter what you do.
In this case, SUBSTRING will perform a bit faster
SELECT CONVERT(date, SUBSTRING('20130909132512', 0, 9), 20)
You'll want to use "20" as the conversion style, though, if you want the date in the format 2013-09-09.

Related

Build a SQL query with a DateTime parameter

I can successfully use a Query with a Date parameter in string format as
SELECT * FROM ORDERS WHERE [DATE]='20160209'
but I haven't seen any sample of a Query specifying a DateTime parameter in string format.
Next samples are rejected by Microsoft SQL Server Management Studio:
SELECT * FROM ORDERS WHERE [DATE]='20130523T153500000Z'
SELECT * FROM ORDERS WHERE [DATE]='2013-05-23T15:35:00:000Z'
I know this is not a good practice and I should pass DateTime values rather than strings, but sometimes it is useful for debugging.
What is the right format to include a string formatted datetime on a SQL query?
No so sure where you've got those date formats...
This one '2013-05-23T15:35:00:000Z' just doesn't seem to be right. I haven't seen that nanoseconds were delimited by a ':' character. It is usually a decimal of a second, so '2013-05-23T15:35:00.000Z' is a better format and it works:
select convert(DateTime,'2013-05-23T15:35:00.000Z')
As for the other, you might need to do the parsing yourself:
select CONVERT(DATETIME,LEFT('20130523T153500000Z',4)+SUBSTRING('20130523T153500000Z',5,2)+SUBSTRING('20130523T153500000Z',7,2))
hope this helps.
Can you just do something like this?
SELECT *
FROM ORDERS
WHERE [DATE] = CONVERT(DATETIME,'20130523T153500000Z')
As long as the string is in a workable format.
If it's just for debugging, you might do something like:
DECLARE #val VARCHAR(25)
-- Easily swapped out with different testing values
SET #val = '20130523T153500000Z'
SELECT *
FROM Orders
WHERE [DATE] = CAST(#val AS DATETIME)
-- You could also use CONVERT

SQL Server Converting varchar to datetime

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

Convert varchar to date with malformed values in SQL Server 2008

This whole date code is beyond my understanding but non the less I need to convert a column in a query result from varchar to date. I have some malformed values and I'm trying to filter them out.
SET DATEFORMAT dmy
SET LANGUAGE us_english
select convert(datetime, some_date, 103)
from some_table
where isdate(some_date) = 1
I keep getting
Conversion failed when converting date and/or time from character string
When querying for the malformed values I get these two records
some_date
---------
621
232
Is there any way to validate the format using isdate ?
Thanks, Frustrated Oracle DBA.
EDIT
Tried #Sean Lange suggestions and indeed it looked promising
select convert(datetime, some_date, 103)
from ( select * from some_table where isdate(some_date) = 1 )
But then I added a where clause
select convert(datetime, some_date, 103)
from ( select * from some_table where isdate(some_date) = 1 )
where convert(datetime, some_date ,103) between
convert(datetime, '01/07/2014')
and convert(datetime,'31/07/2014')
How does a where clause being executed before the from?
Since we know that a valid date looks like dd/mm/yyyy how about a simple structure test?
select convert(datetime, some_date, 103)
from some_table
where len(some_date) = 10 --must have exactly the expected number of characters
This could be expanded upon (depending on requirements)
and some_date like '__/__/____'
Or maybe
and some_date like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'
Anything better would probably need you to put together a custom function that does the CONVERT in a try block, returning NULL in the catch block if its an invalid record. Depends on your requirements...
The problem is happening and will continue to happen because you can't be certain which order the sql engine will take here. One time it might filter the rows first and another time it does the conversion. So what you need to do is force the order the engine works. We can do this by using a CTE to get only the rows we want to convert.
with MyCTE as
(
select some_date
from some_table
where ISDATE(some_date) = 1
)
select CONVERT(datetime, some_date, 103)
from MyCTE
If you're positive that these are the only malformed values and all malformed values will look like this, you could just go ahead and use a hackish CASE statement
SELECT (CASE WHEN LEN(datetime) > 3 THEN convert(datetime, some_date, 103) ELSE NULL),
...
It's really not elegant, but datetimes are notoriously difficult to make elegant because there are so many fragmented formats. If possible, it saves more headaches just to make sure that your data is correctly formatted in the first place through form validation and regex stuff, but since that's not always possible, we have crummy hacks like this to patch ourselves through. Best of luck!

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)

Getting at string data in SQL

I have a row entry with the following format:
Site=[number];this=that;foo=bar;
[number] above can be from 1...infinity. So I need to split out the [number] to use in another select statements where clause. Site=[number] is always at the beginning in the string and the data is always separated by a semi-colon.
declare #t nvarchar(100) = 'Site=230;this=that;foo=bar;';
select convert(int, substring(#t,6, charindex(';',#t,0)-6))
SELECT SUBSTRING(col, 1, CHARINDEX(col,';'))
Why are you storing data in the database in this format? Split it up into columns so that you can do meaningful queries.
You can play with the string this way:
declare #tx as nvarchar(100)
set #tx = 'Site=[number];this=that;foo=bar;'
print substring(
#tx,
CHARINDEX('[', #tx)+1,
CHARINDEX(']',#tx)-CHARINDEX('[',#tx)-1)
Hope this helps.
I don't have MS Sql Server available to try this out, but have you tried something like
Select
field
convert(bigint, substring(field, 6)) as thenum
from
thetable
where
condition=something
where field is the name of the field containing site=[number];...
The theory goes that substring will strip off site= off the beginning, and convert
will (hopefully) convert the number portion and ignore the rest of the text from the semicolon onwards.
It may or may not work. If not you may need to write an elaborate function instead.

Resources