I have following query which takes 2 parameters.
- YearNumber
- MonthNumber
In my pivot query, I am trying to select columns based on @Year_Rtl variable. I need to select data for the year passed, last year and last last year. Since the data being displayed on UI is table format divided by @Year_Rtl, I decided to write a pivot query for that as below.
In the query, it works fine if I hard code [@Year_Rtl], [@Year_Rtl - 1], [@Year_Rtl - 2] to [2012], [2011], [2010]. But since the year passed can be anything, I want columns to be named dynamically.
DECLARE @Month_Rtl int
DECLARE @Year_Rtl int
SET @Year_Rtl = 2012
SET @Month_Rtl = 1
SELECT
'Data 1', [@Year_Rtl], [@Year_Rtl - 1], [@Year_Rtl - 2]
FROM
(SELECT [Yr_No], Qty
FROM dbo.Table1 t
WHERE (t.Col1 = 10) AND
(t.Col2 = '673') AND
((t.Mth_No = @Month_Rtl AND t.Yr_No = @Year_Rtl) OR
(t.Mth_No = 12 AND t.Yr_No IN (@Year_Rtl - 1, @Year_Rtl - 2)))
) p PIVOT (SUM(Qty)
FOR [Yr_No] IN ([@Year_Rtl], [@Year_Rtl-1], [@Year_Rtl-2])
) AS pvt
Above query throws following errors:
Error converting data type nvarchar to smallint.
The incorrect value “@Year_Rtl” is supplied in the PIVOT operator.
Invalid column name ‘@Year_Rtl – 1’.
Invalid column name ‘@Year_Rtl – 2’.
Since you can use dynamic SQL, I’d go with a macro-replacement approach. You’re identifying areas of the query that must be dynamically replaced with placeholders (e.g.
$$Year_Rtl) and then calculating their replacement values below. I find that it keeps the SQL statement easy to follow.