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