Няма да можете да стартирате ALTER VIEW
израз като този във вашата съхранена процедура. Така че, за да разрешите проблема си, трябва да предприемете 2 действия:
1) За да коригирате грешката, която се появява в момента, трябва да започнете CTE с точка и запетая по следния начин:
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
(Или още по-добре започнете да прекратявате всичките си SQL изрази с точка и запетая, тъй като алтернативата е отхвърлена).
2) Преобразувайте израза си за промяна на изгледа в динамичен SQL низ и го изпълнете с помощта на sp_executesql
като ALTER VIEW
изразът трябва да е първият в пакета:
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