¿Cómo convertir una cadena "dd / mm/ aaaa" a datetime en SQL Server?


He intentado esto

SELECT convert(datetime, '23/07/2009', 111)

Pero tengo este error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Sin embargo

SELECT convert(datetime, '07/23/2009', 111)

Está bien aunque

¿Cómo arreglar el 1er?

Author: John Saunders, 2010-05-06

5 answers

El último argumento de CONVERT parece determinar el formato utilizado para el análisis. Consulte MSDN docs para CONVERTIR.

111 - el que está utilizando es Japón yy/mm/dd.

Supongo que el que estás buscando es 103, es decir dd/mm/yyyy.

Así que deberías probar:

 SELECT convert(datetime, '23/07/2009', 103)
 72
Author: Grzegorz Oledzki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-30 21:23:11

Intenta:

SELECT convert(datetime, '23/07/2009', 103)

Este es el estándar británico/francés.

 9
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-06 11:37:50
SELECT convert(varchar(10), '23/07/2009', 111)
 0
Author: RNT665,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-26 12:52:55

SQL Server utiliza por defecto el formato de fecha mdy y así funciona lo siguiente:

SELECT convert(datetime, '07/23/2009', 111)

Y esto no funciona:

SELECT convert(datetime, '23/07/2009', 111)

Yo mismo he estado luchando para llegar a una sola consulta que puede manejar ambos formatos de fecha: mdy y dmy.

Sin embargo, debería estar de acuerdo con el tercer formato de fecha - ymd.

 0
Author: Qwerty-uiop,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-02 00:43:37
SELECT convert(datetime, '23/07/2009', 103)
 0
Author: user6434845,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-07 11:08:00