SQL Server:标量函数不返回任何内容,但它应该返回INT

时间:2014-09-01 17:57:15

标签: sql sql-server function triggers insert

这是我的功能:

CREATE FUNCTION fu_order_customer_adress (@customer_ID INT)
RETURNS INT AS
    BEGIN
        RETURN (
            SELECT c.adress_ID FROM customers AS c
            JOIN orders AS o ON (c.customer_ID = o.customer_ID)
            WHERE c.customer_ID = @customer_ID)
    END

它用于表AFTER INSERT的{​​{1}}触发器,它具有以下结构(没有不重要的列):

orders

orders (order_ID INT, customer_ID INT, employee_ID) 是主键,其他列是外键。

触发器如下所示:

order_ID

以下插入编号后来很容易指出。

1 )这适用于具有不同CREATE TRIGGER tr_orders_insert ON orders AFTER INSERT AS BEGIN DECLARE @order_ID INT = (SELECT order_ID FROM INSERTED); DECLARE @customer_ID INT = (SELECT customer_ID FROM INSERTED); UPDATE orders SET adress_ID = (SELECT dbo.fu_order_customer_adress(@customer_ID)) WHERE order_ID = @order_ID; END 的插页:

customer_ID

2 )但是当插入已使用INSERT INTO orders(customer_ID, employee_ID) VALUES (1, 1) INSERT INTO orders(customer_ID, employee_ID) VALUES (2, 2) 的订单时,insert将以错误结束:

customer_ID

我发现它是由触发器中使用的函数引起的,因为在这种情况下它不会返回任何内容。

我尝试将函数中使用的INSERT INTO orders(customer_ID, employee_ID) VALUES (1, 2) SELECT function放入触发器:

SELECT

在( 1 )中CREATE TRIGGER tr_orders_insert ON objednavka AFTER INSERT AS BEGIN DECLARE @order_ID INT = (SELECT order_ID FROM INSERTED); DECLARE @customer_ID INT = (SELECT customer_ID FROM INSERTED); SELECT c.adress_ID FROM customers AS c JOIN orders AS o ON (c.customer_ID = o.customer_ID) WHERE c.customer_ID = @customer_ID) SELECT dbo.fu_order_customer_adress(@customer_ID) UPDATE orders SET adress_ID = (SELECT dbo.fu_order_customer_adress(@customer_ID)) WHERE order_ID = @order_ID; END 两个结果相同。

在( 2 )中,SELECT结果正常,但SELECT不返回任何内容。

我不明白错误...感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

对于这个简单的触发器我不认为你需要这个性能杀手标量函数你可以简单地执行以下操作而不使用任何标量函数,只需将表与Inserted表连接即可。

此外,您的触发器中的逻辑存在重大问题,它只适用于单个插入,如果Orders表中有多个Insert,则会失败。一种更安全,更高效的方法就像.......

CREATE TRIGGER tr_orders_insert ON orders
AFTER INSERT AS
BEGIN
  SET NOCOUNT ON;

    UPDATE O
       SET O.adress_ID = C.adress_ID
    FROM orders O 
    INNER JOIN inserted  AS I   ON O.order_ID    = I.order_ID 
    INNER JOIN customers AS c   ON C.customer_ID = I.customer_ID         

END