2017-09-19 177 views
0

我對SQL Server中的觸發器非常陌生,所以我希望有人能夠幫助或至少將我指向正確的方向。SQL Server觸發器在插入表之前驗證數據

我有一個表有多個記錄插入到它的作業我想在插入前驗證這些記錄,然後如果它不符合要求raiseerror。

我創建了一個視圖,試圖使之更容易解釋什麼,我試圖做

SELECT TOP (100) PERCENT 
    iJCMasterID, 
    SUM(CASE WHEN ubJCTxSTNoProint = 1 
       THEN fTransQty * ufJCTxSTCustomerCharge 
       ELSE 0 
     END) AS CustCharge, 
    SUM(CASE WHEN iStockID = 5774 THEN 1 ELSE 0 END) AS ValidateJoblot, 
    SUM(CASE WHEN iStockID = 5774 THEN fUnitPriceExcl * fTransQty ELSE 0 END) AS JobTotal 
FROM 
    dbo._btblJCTxLines 
GROUP BY 
    iJCMasterID, dStartDate 
HAVING 
    (SUM(CASE WHEN iStockID = 5774 THEN 1 ELSE 0 END) > 0) 

所以一切都是由iJCMasterID分組,我需要基本確認包含CustCharge = Jobtotal但僅限於工作作業很多是在Having條款進場

如果你需要幫助的任何其他信息,請讓我知道

謝謝你的提前

這是我迄今爲止嘗試,但似乎並不奏效

USE [*******DB] 
GO 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

CREATE TRIGGER [dbo].[ValidateCC] ON [dbo].[_btblJCTxlines] for insert, update AS 

begin 
if exists(select COUNT(*) from inserted)--drop TRIGGER [dbo].[JobOverCreditLimit] 


declare @Jobamount float 

SET @Jobamount = (select sum(fLineTotalExcl) as JobAmount from inserted 
where iStockID = 5774 
GROUP BY inserted.iJCMasterID) 


declare @CCAmount float 

SET @CCAmount = (select sum(fTransQty * ufJCTxSTCustomerCharge) as JobAmount from inserted 
where ubJCTxSTNoProint = 1 
GROUP BY inserted.iJCMasterID) 


declare @Validation float 
set @Validation = (@Jobamount - @CCAmount) 

IF @Validation <> 0 
BEGIN 
DECLARE @EMSG VARCHAR(500) 

SET @EMSG = 'Customer Charge R' + CAST(@CCAmount AS VARCHAR(20))+' does not equal Job Amount R'+ CAST(@CCAmount AS VARCHAR(20))+ '' 
BEGIN 
rollback tran 
RAISERROR (@EMSG ,16, 1) 
end 
END 
end 
+3

爲什麼要存儲該值?爲什麼不在需要時計算它? –

+0

嗨戈登我已經在我原來的帖子上做了一個編輯,實際上並不想將值存儲在另一個表中,只是希望觸發器在插入或引發錯誤之前將其插入帖子中以供引用,但它似乎並不正在工作 –

回答