sql >> Databasteknik >  >> RDS >> Sqlserver

Ändra vy inom lagrad procedur

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



  1. Vilka är de magiska tabellerna i SQL Server 2000?

  2. SQL server 2005 numerisk precision förlust

  3. mysql_fetch_array och endast strängarraynycklar

  4. Force Oracle Drop Global Temp-tabell