Du kommer inte att kunna köra ALTER VIEW
uttalande som det i din lagrade procedur. Så för att lösa ditt problem måste du vidta två åtgärder:
1) För att rätta till felet som för närvarande visas måste du börja CTE med ett semikolon så här:
WITH cte as (
SELECT *,
LAG([pointsRewarded], 1) OVER (PARTITION BY [EmployeeID] ORDER BY [WeekNumber]) as prev1_points,
LAG([pointsRewarded], 2) OVER (PARTITION BY [EmployeeID] ORDER BY [WeekNumber]) as prev2_points,
LAG([pointsRewarded], 3) OVER (PARTITION BY [EmployeeID] ORDER BY [WeekNumber]) as prev3_points
FROM week1)
SELECT *,
CASE WHEN [pointsRewarded] = -10 AND prev1_points = -10 AND prev2_points = -10 AND prev3_points = -10
THEN -200
WHEN [pointsRewarded] = -10 AND prev1_points = -10 AND prev2_points = -10
THEN -100
WHEN [pointsRewarded] = -10 AND prev1_points = -10
THEN -50
ELSE 0
END penalty
FROM cte
(Eller ännu hellre börja avsluta alla dina SQL-satser med semikolon eftersom alternativet är utfasat).
2) Konvertera din alter view-sats till en dynamisk SQL-sträng och kör den med sp_executesql
som ALTER VIEW
uttalandet måste vara det första i partiet:
CREATE PROCEDURE createviewupdatepenaltypointsconsecutive
AS
BEGIN
DECLARE @STMT AS NVARCHAR(MAX) =
'
ALTER VIEW consecutive
AS
WITH cte as (
SELECT *,
LAG([pointsRewarded], 1) OVER (PARTITION BY [EmployeeID] ORDER BY [WeekNumber]) as prev1_points,
LAG([pointsRewarded], 2) OVER (PARTITION BY [EmployeeID] ORDER BY [WeekNumber]) as prev2_points,
LAG([pointsRewarded], 3) OVER (PARTITION BY [EmployeeID] ORDER BY [WeekNumber]) as prev3_points
FROM week1
)
SELECT *,
CASE WHEN [pointsRewarded] = -10 AND prev1_points = -10 AND prev2_points = -10 AND prev3_points = -10
THEN -200
WHEN [pointsRewarded] = -10 AND prev1_points = -10 AND prev2_points = -10
THEN -100
WHEN [pointsRewarded] = -10 AND prev1_points = -10
THEN -50
ELSE 0
END penalty
FROM cte
'
EXEC sp_executesql @STMT;
END