sql >> Database teknologi >  >> RDS >> Sqlserver

Skift visning inden for lagret procedure

Du vil ikke være i stand til at køre ALTER VIEW erklæring som den i din lagrede procedure. Så for at løse dit problem skal du tage 2 handlinger:

1) For at rette den fejl, der vises i øjeblikket, skal du begynde CTE med et semikolon som dette:

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 endnu bedre begynde at afslutte alle dine SQL-sætninger med semikolon, da alternativet er forældet).

2) Konverter din alter view-sætning i en dynamisk SQL-streng og kør den ved hjælp af sp_executesql som ALTER VIEW sætningen skal være den første i batchen:

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



  1. MySQL - Deltag i 2 borde

  2. MySQLIintegrityConstraintViolationException for Hibernate hsql sletning. Kan ikke slette eller opdatere en overordnet række

  3. script, der trækker data fra en txt-fil i where-klausulen

  4. Sådan kontrollerer du nullabilitet i SELECT INTO for bogstavelige kolonner