Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Ändern Sie die Ansicht innerhalb der gespeicherten Prozedur

Sie können ALTER VIEW nicht ausführen Anweisung wie diese in Ihrer gespeicherten Prozedur. Um Ihr Problem zu lösen, müssen Sie also 2 Maßnahmen ergreifen:

1) Um den aktuell auftretenden Fehler zu korrigieren, müssen Sie den CTE mit einem Semikolon wie diesem beginnen:

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

(Oder beginnen Sie noch besser, alle Ihre SQL-Anweisungen mit Semikolon zu beenden, da die Alternative veraltet ist).

2) Konvertieren Sie Ihre alter view-Anweisung in eine dynamische SQL-Zeichenfolge und führen Sie sie mit sp_executesql aus als ALTER VIEW -Anweisung muss die erste im Stapel sein:

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