我对SQL Server中的触发器很新,所以我希望有人可以提供帮助,或者至少指出我正确的方向。
我有一个表,其中插入了多个与我想在插入前验证这些记录的作业相关的记录,如果不符合要求则会报错。
我创建了一个视图,试图让我更容易解释我想要做的事情
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
答案 0 :(得分:0)
如果您想使用触发器进行验证,可以使用INSTEAD OF UPDATE,INSERT
触发器。
有关technet的更多信息:https://technet.microsoft.com/en-us/library/ms179288(v=sql.105).aspx