在SQL Server中插入后更新触发器c#

时间:2015-03-02 01:29:27

标签: sql sql-server triggers

以下是我一直坚持的情景:

  • 用户将书籍插入书籍表
  • 书籍收藏更新了用户ID和bookscollection中的INSERTED bookid

Userid从c#application中的字符串用户名传递。

bookcollection bookc_id, bookc_bookid, bookc_bookuser
books bookid, title, author, year
users userid, username, password

bookid是bookc_bookid的外键

userid是bookc_bookuser的外键

这是它如何插入书籍表

INSERT INTO books (title, author, year) VALUES (@title, @author, @year);

在上一个表单中,我使用了INNER JOIN子句,根据登录的用户名字符串从books集合中检索信息。

 SELECT * FROM bookcollection c 
 INNER JOIN users r ON c.bookC_userid = r.userid 
 INNER JOIN books b ON c.bookC_bookID = b.bookid 
 WHERE username LIKE '" + Username + "'"

我如何创建一个触发器,用于使用userid和bookid更新books表。

1 个答案:

答案 0 :(得分:0)

简单,您可以创建更新触发器像这样

CREATE TRIGGER yourtriggername
     ON yourtablename
     AFTER  INSERT
AS
BEGIN
 /* here goes your update statement*/
   UPDATE c
   SET c.bookC_userid = r.userid,
   b.bookC_bookID= b.bookid 
   FROM bookcollection c 
   INNER JOIN users r ON c.bookC_userid = r.userid 
   INNER JOIN books b ON c.bookC_bookID = b.bookid
   Where b.bookid = SCOPE_IDENTITY(); 
end 

修改:您可以通过Scope_Identity函数

获取新插入的您的ID