Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Ubah Tampilan dalam prosedur tersimpan

Anda tidak akan dapat menjalankan ALTER VIEW pernyataan seperti itu dalam prosedur tersimpan Anda. Jadi untuk memecahkan masalah Anda, Anda harus mengambil 2 tindakan:

1) Untuk memperbaiki kesalahan yang saat ini muncul, Anda harus memulai CTE dengan titik koma seperti itu:

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

(Atau lebih baik mulai mengakhiri semua Pernyataan SQL Anda dengan titik koma karena alternatifnya tidak digunakan lagi).

2) Ubah pernyataan tampilan perubahan Anda dalam string SQL dinamis dan jalankan menggunakan sp_executesql sebagai ALTER VIEW pernyataan harus yang pertama dalam kumpulan:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. C# Setara dengan Tipe Data SQL Server

  2. Bagaimana Melakukan KIRI SEMI BERGABUNG di SQL Server

  3. Cara Mengubah Tabel di SQL Server dengan Menggunakan Alter Statement - Tutorial SQL Server / T-SQL Part 35

  4. Rata-rata pergerakan jendela di server sql

  5. Bagaimana cara menambahkan kolom nomor urut ke dalam data hasil?