INSERT INTO View,INSTEAD OF Trigger,Identity,multiple tables?

时间:2013-03-01 15:35:11

标签: sql-server view triggers

这里是我的表(Entier = Integer //Caractèrelongvariable = Varchar):

http://i.stack.imgur.com/lNjyy.jpg

enter image description here

我创建了一个视图V_Enterprise(idContact,phoneNumber,email,name,city,adress)

我尝试在该视图上创建一个Trigger,以允许用户更新视图:

CREATE TRIGGER test
ON V_Entreprise
INSTEAD OF INSERT
AS 
DECLARE @T_ContactId INT
BEGIN
    INSERT INTO T_Contact 
    SELECT i.phoneNumber, i.email
    FROM Inserted i 

    SELECT @T_ContactId = @@IDENTITY

    INSERT INTO T_Entreprise
    SELECT @T_ContactId, i.name, i.city, i.adress
    FROM Inserted i 
END ;

正如我所料,它适用于简单插入,但是当我一次添加几行时,它会失败,因为@T_ContactId只包含第一个id。有人可以帮我解决吗?我觉得我应该使用INNER JOIN插入,但我无法弄清楚如何处理它。

4 个答案:

答案 0 :(得分:2)

好的,你永远不应该将标量变量设置为触发器中插入或删除的值。

使用OUTPUT子句来获取您的id值。

答案 1 :(得分:1)

此触发器使用游标上的循环,并且不需要表中的任何特定唯一性;

CREATE TRIGGER test
ON V_Enterprise
INSTEAD OF INSERT
AS 
BEGIN
   DECLARE @name    VARCHAR(32)
   DECLARE @city    VARCHAR(32)
   DECLARE @address VARCHAR(32)
   DECLARE @pn      VARCHAR(32)
   DECLARE @email   VARCHAR(32)

   DECLARE cursor1 CURSOR FOR
      SELECT name,city,address,phoneNumber,email FROM inserted;

    OPEN cursor1;
    FETCH NEXT FROM cursor1 INTO @name, @city, @address, @pn, @email;
    WHILE @@FETCH_STATUS = 0
    BEGIN
      INSERT INTO T_Contact (phoneNumber,email) VALUES (@pn, @email);
      INSERT INTO T_Enterprise (idcontact,name,city,address) VALUES
         (@@IDENTITY,@name,@city,@address);
      FETCH NEXT FROM cursor1 INTO @name, @city, @address, @pn, @email;
    END
    CLOSE cursor1;
    DEALLOCATE cursor1;
END
GO

答案 2 :(得分:1)

我不知道这是否是一种良好的方式,但您可以在不依赖于唯一列或使用INSERT的OUTPUT子句使用游标的情况下执行此操作。这种方法确实利用了一个内存临时表,它可以在大插入时变大。

DECLARE @Table table( NewID BIGINT);


INSERT INTO T_Contact (PhoneNumber) 
    OUTPUT Inserted.ID
    INTO @Table
SELECT PhoneNumber FROM inserted WHERE 
;

INSERT INTO T_Enterprise (Contact_ID)
SELECT NewID FROM @Table;

答案 3 :(得分:0)

如果phoneNumberemailT_Contact中的唯一键,那么您可以这样做:

CREATE TRIGGER test
ON V_Entreprise
INSTEAD OF INSERT
AS 
DECLARE @T_ContactId INT
BEGIN
    INSERT INTO T_Contact 
    SELECT i.phoneNumber, i.email
    FROM Inserted i 

    SELECT @T_ContactId = @@IDENTITY

    INSERT INTO T_Entreprise
    SELECT
        (SELECT idContact FROM T_Contact
            WHERE phoneNumber = i.phoneNumber AND email = i.email),
        i.name, i.city, i.adress
    FROM Inserted i 
END ;