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

perbarui pemicu untuk memperbarui catatan di tabel lain

Anda akan membutuhkan sesuatu seperti ini - berbasis set solusi yang memperhitungkan bahwa dalam UPDATE pernyataan, Anda mungkin memperbarui beberapa baris sekaligus, dan karena itu pemicu Anda juga harus menangani beberapa baris di Inserted dan Deleted tabel.

CREATE TRIGGER [dbo].[updateUserId] 
ON [dbo].[User_TB]
FOR UPDATE
AS 
    -- update the "Break" table - find the rows based on the *old* User_Id
    -- from the "Deleted" pseudo table, and set it to the *new* User_Id
    -- from the "Inserted" pseudo table
    SET User_Id = i.User_Id 
    FROM Inserted i
    INNER JOIN Deleted d ON i.TID = d.TID
    WHERE
        Break_TB.User_Id = d.User_Id

    -- update the "Log" table - find the rows based on the *old* User_Id
    -- from the "Deleted" pseudo table, and set it to the *new* User_Id
    -- from the "Inserted" pseudo table
    UPDATE Break_TB 
    SET User_Id = i.User_Id 
    FROM Inserted i
    INNER JOIN Deleted d ON i.TID = d.TID
    WHERE
        Break_TB.User_Id = d.User_Id

Kode ini mengasumsikan bahwa TID kolom di User_TB tabel adalah kunci utama yang tetap sama selama pembaruan (sehingga saya dapat menggabungkan nilai-nilai "lama" dari Deleted tabel semu dengan nilai "baru" setelah pembaruan, disimpan di Inserted tabel semu)




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Apakah ada masalah Performa saat menggunakan ISNULL() di SQL Server?

  2. SQL Server:gunakan parameter di CREATE DATABASE

  3. Hentikan Access dari menggunakan identitas yang salah saat menambahkan ke tabel tertaut di server SQL

  4. Bagaimana saya bisa MEMASUKKAN data ke dalam dua tabel secara bersamaan di SQL Server?

  5. Ubah format Tanggal menjadi format DD/MMM/YYYY di SQL Server