0

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)"

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kelaynak
  • 5
  • 4
  • Your query has no table. It needs a `from`. `select dateadd(...) FROM some_table`. Also be sure to use bind parameters rather than string concatenation to add values to a SQL query; see https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python – Schwern Jan 09 '21 at 09:01

1 Answers1

-1

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

Seppukki
  • 563
  • 2
  • 8
  • 24