I've got a query that works perfectly when run on its own and returns what I need it to. When I try to wrap it into a view as displayed below, I'm getting an error "Must declare the table variable "@AwdYrTbl"
I'm sure this is some kind of syntax thing I'm doing wrong. How can I fix it?
I'm sure this is some kind of syntax thing I'm doing wrong. How can I fix it?
SQL:
-- DECLARE VARIABLES
Declare @TodayYr VARCHAR (4)
Declare @TodayMn VARCHAR (2)
Declare @2Years VARCHAR (4)
Declare @LastYr VARCHAR (4)
Declare @NextYr VARCHAR (4)
Declare @AwdYr1 VARCHAR (7)
Declare @AwdYr2 VARCHAR (7)
Declare @AwdYr3 VARCHAR (7)
Declare @AwdYr4 VARCHAR (7)
-- DECLARE VARIABLE TABLE TO STORE THE YEARS
DECLARE @AwdYrTbl TABLE
(AwdYr VARCHAR(7),
YearID VARCHAR(2),
Nbr VARCHAR(1))
-- SET VARIABLES
SET @TodayYr = YEAR(getdate())
SET @TodayMn = MONTH(getdate())
SET @2Years = YEAR(getdate())-2
SET @LastYr = YEAR(getdate())-1
SET @NextYr = YEAR(getdate())+1
-- SET AWARD YEARS
SET @AwdYr1 = @2Years + '-' + RIGHT(@LastYr,2)
SET @AwdYr2 = @LastYr + '-' + RIGHT(@TodayYr,2)
SET @AwdYr3 = @TodayYr + '-' + RIGHT(@NextYr,2)
SET @AwdYr4 = @NextYr + '-' + RIGHT(@NextYr + 1,2)
-- POPULATE THE VARIABLE TABLE WITH YEAR VALUES ABOVE BASED ON RUN-TIME MONTH
IF @TodayMn IN (1)
INSERT INTO @AwdYrTbl
SELECT @AwdYr1,RIGHT(@AwdYr1,2),'1' UNION ALL SELECT @AwdYr2,RIGHT(@AwdYr2,2),'2'
ELSE IF @TodayMn IN (2,3,4)
INSERT INTO @AwdYrTbl
SELECT @AwdYr1,RIGHT(@AwdYr1,2),'1' UNION ALL SELECT @AwdYr2,RIGHT(@AwdYr2,2),'2' UNION ALL SELECT @AwdYr3,RIGHT(@AwdYr3,2),'3'
ELSE INSERT INTO @AwdYrTbl
SELECT @AwdYr2,RIGHT(@AwdYr2,2),'1' UNION ALL SELECT @AwdYr3,RIGHT(@AwdYr3,2),'2'
SELECT * FROM @AwdYrTbl
EXEC('CREATE VIEW vw_Dynamic_Year AS SELECT * FROM @AwdYrTbl')