0

I Have a query where I have a parameter which I am declaring as :

declare @year varchar(10)='F2016/2017'
select forecast - lag(forecast, 1, 0)over(partition by id order by id, date) as @year - 1

Here I am getting the difference for the column forecast and want the column to be named as F2015/2016.

Is there a way I can do this ??

Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
Alice
  • 17
  • 6
  • If you are using `lag()` you are using a supported version of SQL Server. I fixed the tags. – Gordon Linoff Jul 27 '20 at 16:13
  • You'll need to use Dynamic SQL. Typically you'll create a stored procedure with the dynamic query in it, instead of calling the query directly. – The Impaler Jul 27 '20 at 16:47
  • All output column names must be known at compile time, which means that it can't come from a variable. The only solution is to create a dynamic @SQL variable, and then [`EXEC` or `sp_executesql` it](https://stackoverflow.com/a/14722333/1220550) – Peter B Jul 27 '20 at 16:49
  • 1
    I would suggest returning the column names in a semantically appropriate but generic format (eg "yearminus1"), and renaming them in your presentation layer/client code. – allmhuran Jul 27 '20 at 17:41

0 Answers0