0

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'. I need to convert it to datetime format first. The following SQL query is made using pyodbc:

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?

1 Answer 1

2

string literals are delimited by single quotes in SQL Server by default. 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".

this will fix the error you are receiving.

Invalid column name '2017-10-8 00:00:00'

The CONVERT (datetime, startDate, 120) will make your query unsargable by the way. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Martin. I want to select a certain period of startDate. Are there any methods to do that if I cannot change the datatype of the database table?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.