可组合DML错误

时间:2011-12-16 02:50:00

标签: c# sql sql-server-2008

我有以下可组合的dml,我似乎无法设置它的工作。有人可以帮我指出我出错的地方吗?

INSERT INTO order_kit (kit_no, order_id) 
SELECT 
    X.kit_no, 10089 
FROM 
    (
    MERGE INTO kit AS tgt 
    USING
        (SELECT TOP 2 kit_no 
         FROM kit rk, batch rb 
         WHERE rk.study_id = 35 AND 
         rk.batch_id = rb.batch_id AND 
         rb.depot_id = 16 AND 
         rk.treatment = 1 AND 
         rk.status = 1 AND 
         rb.status = 1 AND 
         rb.expiry > CAST(FLOOR(CAST(getdate() AS float)) AS datetime)
         ) AS src ON tgt.kit_no = src.kit_no 
         WHEN MATCHED THEN 
            UPDATE SET status = 6 OUTPUT $action as action, kit_no) AS X

列名'kit_no'无效。 (*在最后一行)

当FROM子句包含嵌套的INSERT,UPDATE,DELETE或MERGE语句时,INSERT语句的目标表'order_kit'不能位于(主键,外键)关系的任何一侧。找到参考约束'FK_order_kit_order'。

3 个答案:

答案 0 :(得分:2)

当你没有提供你的表定义时很难猜到,但我猜第一个错误是因为你有一个不合格的kit_no。做到这一点

SELECT TOP 2 rk.kit_no

看看会发生什么。

另外,我认为第二个错误很明显。

答案 1 :(得分:1)

您必须在输出子句中限定kit_no

OUTPUT $action as action, src.kit_no

我实际上不明白你怎么能得到这两个错误。 SQL Server通常只会在查询时抱怨一件事。

您可以通过创建output into的表变量来解决第二个问题,并使用该表变量作为源来将行插入order_kit

<强>更新

您可以使用更新而不是合并来简化此操作,并将输出直接输入order_kit

update top (2) rk
set [status] = 6
output inserted.kit_no, 10089 into order_kit(kit_no, order_id)
from kit as rk
  inner join batch as rb
    on rk.batch_id = rb.batch_id 
where
  ...

答案 2 :(得分:0)

我设法通过使用

解决了这个问题
INSERT INTO order_kit (kit_no, order_id) 
SELECT 
    X.kit_no, 10089 
FROM 
    (
    MERGE INTO kit AS tgt 
    USING
        (SELECT TOP 2 kit_no 
         FROM kit rk, batch rb 
         WHERE rk.study_id = 35 AND 
         rk.batch_id = rb.batch_id AND 
         rb.depot_id = 16 AND 
         rk.treatment = 1 AND 
         rk.status = 1 AND 
         rb.status = 1 AND 
         rb.expiry > CAST(FLOOR(CAST(getdate() AS float)) AS datetime)
         ) AS src ON tgt.kit_no = src.kit_no 
         WHEN MATCHED THEN 
            UPDATE SET status = 6 OUTPUT $action as action, **tgt.kit_no**) AS X