11

这对我有用

MERGE Table1 AS tgt
USING
(
    SELECT
        TOP 1
        *
    FROM
        Table2,
        (
            SELECT
                itmid
            FROM
                Table3
            WHERE
                id = @id
        ) as a
    WHERE
        id = @id
) AS src
ON ( tgt.id = src.id )
WHEN MATCHED THEN
    UPDATE SET qty = qty + @qty
WHEN NOT MATCHED THEN
    INSERT itmid
    VALUES itmid;

但是当我这样改变时,它不起作用,最后显示错误select

MERGE Table1 AS tgt
USING
(
    SELECT
        TOP 1
        *
    FROM
        Table2
    WHERE
        id = @id
) AS src
ON ( tgt.id = src.id )
WHEN MATCHED THEN
    UPDATE SET qty = qty + @qty
WHEN NOT MATCHED THEN
    INSERT itmid
    SELECT itmid FROM Table3 WHERE id = @id;
4

2 回答 2

12

根据MSDN 文档

<merge_not_matched>::=
{
    INSERT [ ( column_list ) ] 
        { VALUES ( values_list )
        | DEFAULT VALUES }
}

INSERT from 的语法SELECT如下:

  WHEN NOT MATCHED THEN
            INSERT itmid SELECT itmid FROM Table3 WHERE id=@id;

不被允许!

我会尝试通过与Table3.

于 2013-02-01T13:14:04.427 回答
-4

做这个

 MERGE Table1 AS tgt
 USING (SELECT TOP 1 * FROM Table2
        WHERE id = @id) AS src
ON (tgt.id = src.id)
            WHEN MATCHED THEN UPDATE SET qty = qty + @qty
            WHEN NOT MATCHED THEN
                INSERT (itmid) 
                 SELECT itmid FROM Table3 WHERE id=@id;

根据http://msdn.microsoft.com/en-us/library/bb522522(v=sql.105).aspx应该可以正常工作

对不起,我解释错了,我原来的答案是

MERGE Table1 AS tgt
     USING (SELECT TOP 1 * FROM Table2
            WHERE id = @id) AS src
    ON (tgt.id = src.id)
                WHEN MATCHED THEN UPDATE SET qty = qty + @qty
                WHEN NOT MATCHED THEN
                    INSERT (itmid) values (SELECT top 1 itmid FROM Table3 WHERE id=@id);

由于合并插入一次需要一个插入,并且多次插入可能会失败。

于 2013-02-01T12:47:04.103 回答