Python Forum

Full Version: selecting from database using sql query by year
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everybody,

I've got a question. I'm creating a query for a SQL database. Here is my query:

StartGesprek looks like '2018-07-11 15:54:40'
query="SELECT StartGesprek FROM dbo.tbl WHERE StartGesprek[:4]='2018'"

as you can see I want to select just the first 4 characters from StartGesprek but I get an error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near ':4'. (102)

I can not find anything on Google (or I'm not looking for the right thing.

I hope you bright boys and girls know the answer.
StartGesprek[:4] is Python syntax, it's not SQL syntax. Everything in the query has to be SQL syntax. You would want something more like left(StartGesprek, 4).
Cheers, I will look into that.
Is StartGesprek actually a varchar column, though? If it's a datetime2 (as it should be, if it's holding dates), then string manipulation won't work with it. But that's fine, because you have better options if it's a date.

Try this: where year(tbl.StartGesprek) = 2018
I solved it by using:
if row[0].year==int(jaar)
.

Thanks for replying.