我有这个触发器
alter trigger fuzzylogic on oehdrhst_sql
for insert
as
begin
declare @ordno char(8)
declare @rownum int
declare @id int
select @ordno = ord_no from inserted
select @rownum = a.id from banktransactions a where convert(char(8),a.OwnReference) = (select ord_no from inserted)
select @id = a.id from banktransactions a join inserted i on i.ord_no = a.invoicenumber
where a.invoicenumber = @ordno
begin
insert into triggertest values(@ordno,@rownum,@id)
update banktransactions set matchid = @rownum,SupplierInvoiceNumber = @ordno where id = @id
end
end
当我在插入一行后查看triggertest时,我看到了ordno和rownum,但我一直在id上找到空值
我运行这个sql语句进行测试,看看查询是否会返回任何内容,但确实如此。
select a.id from banktransactions a join oehdrhst_sql b on a.invoicenumber = b.ord_no
为什么不打印变量?
答案 0 :(得分:1)
从插入的
中选择@ordno = ord_no
这种逻辑从根本上是有缺陷的。如果插入多行,您希望将哪个值赋给变量?这将是任意的。触发每个语句,而不是每行。
您需要更新触发器以处理多行插入。如果没有模式,样本数据和期望的结果,这是对您应该使用的触发逻辑的疯狂模糊猜测,而不是从inserted
分配任意行:
ALTER TRIGGER dbo.fuzzylogic -- always use dbo prefix!
ON dbo.oehdrhst_sql -- always use dbo prefix!
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.triggertest -- always use schema prefix!
-- where is your column list?
SELECT i.ord_no, b1.id, b2.id
FROM inserted AS i
INNER JOIN dbo.banktransactions AS b1 -- always use schema prefix!
ON i.ord_no = CONVERT(CHAR(8), b1.OwnReference)
INNER JOIN dbo.banktransactions AS b2 -- always use schema prefix!
ON i.ord_no = b2.invoicenumber;
UPDATE b
SET matchid = b1.id, SupplierInvoiceNumber = i.ord_no
FROM dbo.banktransactions AS b
INNER JOIN dbo.banktransactions AS b2 -- always use schema prefix!
ON b.id = b2.id
INNER JOIN inserted AS i
ON i.ord_no = b2.invoicenumber
INNER JOIN dbo.banktransactions AS b1 -- always use schema prefix!
ON i.ord_no = CONVERT(CHAR(8), a.OwnReference);
END
GO
这可能是完全错误的,但是如果没有更深入地了解您的系统(或者为什么银行交易表中的三个不同的行应该相关 - 哎呀!),这很难说。它至少应该给你一个开始。