有關觸發器的問題-一次插入多條

來源:互聯網
上載者:User

需求:寫了一個FOR INSERT的觸發器,每次插入資料的時候向相關的資料表中也同時插入資料。
問題:測試的時候,一次只向主表中插入一條記錄,那麼觸發器沒有問題。在實際使用的時候,因為使用了insert into select語句,一次向主表中插入了超過一條的記錄,如17條,但是發現其他資料表中卻都只有一條記錄,明顯出現了錯誤。
解決:
1、上網查詢“一次插入多條”這樣的關鍵字
2、通過在觸發器中書寫:select count(*) from inserted,的確可以看到一次插入了多條
3、網上說用“遊標”來實現
分析:
1、其實不用右邊也可以,如果只是把插入的資料直接插入其他相關的資料表,完全可以使用insert into (select from inserted)來實現。
例如:
CREATE TRIGGER TriInsertStoreFile ON tblStore
FOR INSERT
AS

BEGIN
  Insert into storeFile(storeID) (SELECT storeID FROM INSERTED)
END
2、而我在實際應用中,還存在與storeFile關聯的storeFileItem資料表,要用插入storeFile時自動產生的主鍵FileID,插入storeFileItem中作為外部索引鍵關聯,看來只有用"遊標"了,其實也不難

CREATE TRIGGER TriInsertStoreFile ON tblStore
FOR INSERT
AS

DECLARE @storeID int
DECLARE @FILEID int

SET @storeID=0
SET @FILEID=0

DECLARE stores_cursor CURSOR FOR
SELECT storeID FROM Inserted

OPEN stores_cursor

FETCH NEXT FROM stores_cursor
INTO @storeID

WHILE @@FETCH_STATUS = 0
BEGIN
  Insert into storeFile(storeID) (SELECT storeID FROM INSERTED)
  SET @FILEID=@@identity
  Insert into storeFileItem(fileID) values(@FILEID)
END

CLOSE stores_cursor
DEALLOCATE stores_cursor

總算解決問題。
最後能把對其他資料表的插入寫在單獨的預存程序中,就更理想了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.