0

我有我做的这个触发器

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

为什么不打印变量?

4

1 回答 1

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

这可能是完全错误的,但是如果不深入了解您的系统(或者为什么银行交易表中的三个不同行应该相关 - 哎呀!),就很难说清楚。它至少应该给你一个开始。

于 2013-08-28T20:16:35.213 回答