简体   繁体   English

在SQL查询中转换日期时间

[英]convert datetime in SQL query

I want to select records within a period of date. 我想在一段时间内选择记录。 However, the corresponding data type in database is like '2017-11-13-05-36-25'. 但是,数据库中的相应数据类型类似于“ 2017-11-13-05-36-25”。 I need to convert it to datetime format first. 我需要先将其转换为日期时间格式。 The following SQL query is made using pyodbc: 使用pyodbc进行以下SQL查询:

connection = pyodbc.connect("Driver={\
ODBC Driver 13 for SQL Server};\
Server=server1,\
100;Database=my_db;\
Uid=abc;\
Pwd=123;\
Encrypt=yes;\
TrustServerCertificate=no;\
Connection Timeout=30;")

cmd = r'SELECT startDate FROM table1 where \
CONVERT (datetime, startDate, 120) between \
CONVERT(datetime, "2017-10-8 00:00:00", 120) and \
CONVERT(datetime,"2017-11-7 00:00:00", 120)'

a = pd.read_sql(cmd, con = connection)

After execution, I received the following error: 执行后,我收到以下错误:

Error: ('42S22', "[42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name '2017-10-8 00:00:00'. (207) (SQLExecDirectW)")

How can get the correct result? 如何获得正确的结果?

string literals are delimited by single quotes in SQL Server by default. 默认情况下,字符串文字在SQL Server中由单引号分隔。 Double quotes denote an identifier such as column or object name. 双引号表示标识符,例如列或对象名称。

So instead of "2017-10-8 00:00:00" use '2017-10-8 00:00:00' and same for "2017-11-7 00:00:00" . 因此,而不是"2017-10-8 00:00:00"使用'2017-10-8 00:00:00'和同为"2017-11-7 00:00:00"

this will fix the error you are receiving. 这样可以解决您收到的错误。

Invalid column name '2017-10-8 00:00:00' 无效的列名'2017-10-8 00:00:00'

The CONVERT (datetime, startDate, 120) will make your query unsargable by the way. 顺便说一下CONVERT (datetime, startDate, 120)将使您的查询无法进行。 It won't be able to do an index range seek on that column. 它将无法在该列上进行索引范围查找。 startDate should use a suitable datatype ( date / datetime / datetime2 ) such that it doesn't need to be converted at run time. startDate应该使用合适的数据类型( date / datetime / datetime2 ),这样就不需要在运行时进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM