2010-04-30 68 views
3
ALTER TRIGGER [dbo].[TR_O_SALESMAN_INS] 
    ON [dbo].[O_SALESMAN] 
    AFTER INSERT 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    -- Insert statements for trigger here 
    DECLARE @SLSMAN_CD NVARCHAR(20) 
    DECLARE @SLSMAN_NAME NVARCHAR(20) 
    SELECT @SLSMAN_CD = SLSMAN_CD,@SLSMAN_NAME=SLSMAN_NAME 
    FROM INSERTED 

    IF NOT EXISTS(SELECT * FROM O_SALESMAN_USER WHERE SLSMAN_CD = @SLSMAN_CD) 
    BEGIN 
     INSERT INTO O_SALESMAN_USER(SLSMAN_CD, PASSWORD, USER_CD) 
     VALUES(@SLSMAN_CD, @SLSMAN_CD,@SLSMAN_NAME) 
    END 
END 

這是一個table(O_SALESMAN)書面從中獲取幾列,並將其插入到彼此table(O_SALESMAN_USER)觸發。目前通過存儲過程將批量數據插入到​​表中,其中觸發器只被觸發一次,並且O_SALESMAN_USER每次存儲過程執行時都只插入一條記錄,我希望在每個存儲過程執行後觸發器運行記錄,插入到​​,這樣兩個表應該有相同的計數,這是沒有發生..所以請讓我知道什麼可以在此觸發器修改,以實現相同...發射扳機的批量插入

+0

可能是值得你澄清是否意味着BULK INSERT(HTTP://msdn.mic rosoft.com/en-us/library/ms188365.aspx),您需要包含FIRE_TRIGGERS,或者簡單地使用多行INSERT(http://msdn.microsoft.com/zh-cn/library/ms174335.aspx) – 2010-04-30 06:54:54

回答

1

是的,觸發器觸發一次聲明,而不是每行一次。

所以,你需要這樣的東西:

SET NOCOUNT ON 

INSERT INTO O_SALESMAN_USER(SLSMAN_CD, PASSWORD, USER_CD) 
SELECT 
    i.SLSMAN_CD,i.SLSMAN_CD,i.SLSMAN_NAME 
FROM 
    inserted i 
     left join 
    O_SALESMAN_USER u 
     on 
      i.SLSMAN_CD = u.SLSMAN_CD 
where 
    u.SLSMAN_CD is NULL 
0

我之情況是,(表名:股票,StockLog)

我通過存儲過程將庫存表內的散裝行,想也有所有這些行StockLog表內

起初我是因爲使用

做一樣的你(通過變量)我的INSERT觸發器內的存貨表 ,但得到的錯誤
DECLARE @StocklId bigint 

SET @StocklId = (SELECT StocklId FROM inserted) 

我有多個值(SELECT StocklId FROM插入),因爲我是插入多行,然後我刪除所有變量, 和我現在做這個

INSERT INTO StockLog(StocklId,PharmacyId,TransactionDetailId,ProductId,TotalQty,ReservedQty,AvailableQty,strUserName,strTerminalName,strVer) 

SELECT StocklId, PharmacyId, TransactionDetailId, ProductId, TotalQty, 0, AvailableQty,strUserName, strTerminalName, strVer FROM inserted 

,現在一切都很好

5

你可以使用光標如下:

create trigger trg_insertstuff 
on [O_SALESMAN] 
after insert 
as 

    DECLARE @SLSMAN_CD NVARCHAR(20) 
    DECLARE @SLSMAN_NAME NVARCHAR(20) 


declare db_cursor CURSOR FOR 
SELECT SLSMAN_CD, SLSMAN_NAME 
from inserted 

OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @SLSMAN_CD , @SLSMAN_NAME 

WHILE @@FETCH_STATUS = 0 
BEGIN 

IF NOT EXISTS(SELECT * FROM O_SALESMAN_USER WHERE SLSMAN_CD = @SLSMAN_CD) 
    BEGIN 
     INSERT INTO O_SALESMAN_USER(SLSMAN_CD, PASSWORD, USER_CD) 
     VALUES(@SLSMAN_CD, @SLSMAN_CD,@SLSMAN_NAME) 
    END 


FETCH NEXT FROM db_cursor INTO @SLSMAN_CD , @SLSMAN_NAME 
end 

CLOSE db_cursor 
DEALLOCATE db_cursor 
+2

http://msdn.microsoft.com/en-us/library/ms190752.aspx「我們不建議在觸發器中使用遊標,因爲它們可能會降低性能。要設計影響多行的觸發器,請使用基於行集的邏輯而不是光標。「 – 2014-06-04 13:15:46