0

I am trying to use date data type as a variable in a select query , I would want to replace the date column name dynamically by declaring it as a variable but this fails with a syntax error.

DECLARE @DATE_VAR VARCHAR(10) SET @DATE_VAR = 'Visit_date'
--print @date_var

SELECT @DATE_VAR from Maternity_DB.dbo.Visit_table
WHERE @Date_Var> getdate() - 10
Thom A
  • 88,727
  • 11
  • 45
  • 75
  • You want a dynamic sql. A lot of examples can be found over here. – Serg Feb 23 '22 at 11:22
  • Do you mean `@DATE_VAR` is the column name to be used in the `SELECT` query? It's a long read but I suggest you peruse [this article](https://www.sommarskog.se/dynamic_sql.html) before going down the dynamic SQL path. – Dan Guzman Feb 23 '22 at 11:25
  • Does this answer your question? [SQL: Select dynamic column name based on variable](https://stackoverflow.com/questions/5637983/sql-select-dynamic-column-name-based-on-variable) – Thom A Feb 23 '22 at 11:34
  • Additionally to the above helpful comments, if you try to search the internet for examples, don't use "data type", because what you want to be dynamic is not that, it is "column" or "field". – Dávid Laczkó Feb 23 '22 at 11:41

0 Answers0