Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use TO_DATE in SQL Server 2012

I have a problem. When I execute this SQL statement in SQL Server 2012:

TO_DATE('2011-11-09 00:00:00','YYYY-MM-DD HH24:MI:SS')

I get an error:

'TO_DATE' not is a name de function integrate recognized.

What is the solution?

Thanks!

like image 252
María José Luna Rego Avatar asked Jul 13 '17 07:07

María José Luna Rego


People also ask

What is TO_DATE function in SQL Server?

Introduction to SQL TO_DATE() TO_DATE() function in most SQL database management servers such as PostgreSQL and ORACLE is used to convert data values of character data types such as VARCHAR, NVARCHAR, CHAR etc. to standard DATE data type.

How do I convert a string to a date in SQL Developer?

SELECT TO_DATE('2015/05/15 8:30:25', 'YYYY/MM/DD HH:MI:SS') FROM dual; This would convert the string value of 2015/05/15 8:30:25 to a date value.

How do I convert text to date in SQL?

SQL Server: Convert string to date explicitly In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.


3 Answers

SQL-Server has no TO_DATE function. You have to use convert. See here

-- Specify a datetime string and its exact format
SELECT TO_DATE('2012-06-05', 'YYYY-MM-DD') FROM dual;


-- Specify a datetime string and style 102 (ANSI format), raises an error if conversion fails
  SELECT CONVERT(DATETIME, '2012-06-05', 102);

  -- TRY_CONVERT available since SQL Server 2012 (returns NULL if conversion fails)
  SELECT TRY_CONVERT(DATETIME, '2012-06-05', 102);

For your specific case use:

convert(DATETIME, '2011-11-09 00:00:00')
like image 177
Jens Avatar answered Oct 13 '22 00:10

Jens


TO_DATE() isn't a valid function in SQL Server (T-SQL)

The alternatives depend on what version of SQL Server you are using

CAST() or CONVERT() may be used in any version. Starting with SQL Server 2012 onward one can use TRY_CAST() or TRY_CONVERT(). The advantage of using the latter pair is they do not error if the strings cannot be converted when they return null instead.

For date/time strings generally using CONVERT() or TRY_CONVERT() is used as you can pass "style" numbers where YYYY-MM-DD is "style" 102 e.g.

SELECT TRY_CONVERT(DATE,'2017-01-21',102)

However it is possible to use CAST/TRY_CAST like this example:

SET DATEFORMAT mdy;  
SELECT TRY_CAST('12/31/2016' AS datetime)
like image 44
Paul Maxwell Avatar answered Oct 13 '22 01:10

Paul Maxwell


CONVERT In Sql Server Can Do The Same Job Of TO_DATE In Oracle

SELECT CONVERT(date, yourDate ,104)
like image 1
Abd Abughazaleh Avatar answered Oct 13 '22 01:10

Abd Abughazaleh