Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to write a SQL statement in Python: 'attribute' is a column name that I want to change its format and I am giving it as a parameter. Because its name can be different.

cur.execute("SELECT DATEADD(y," + attribute + ", '1980-01-01')")

But I am getting below error. attribute=Date1 and this column exists.

[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'Date1'. (207) (SQLExecDirectW)"

question from:https://stackoverflow.com/questions/65640822/getting-error-that-invalid-column-name-while-writing-sql-statement-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
441 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understand your code correctly, you're building the string in the cur.execute command. If your python is up-to-date, try using fstrings. They are a bit more readable and you don't get the messy code with all the quotes. If your python version doesn't support substrings, try building the request in a variable to make the code a bit more readable.
Possible solution:
cur.execute(f"SELECT DATEADD(y, {attribute}, '1980-01-01')")
The string will result in SELECT DATEADD(y, Date1, '1980-01-01')
There is also a FROM missing from the query, the error Invalid column is correct because you don't tell where to find that column


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...