使用select语句合并插入

时间:2013-02-01 12:44:07

标签: sql sql-server merge sql-server-2008-r2

这对我有用

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;

2 个答案:

答案 0 :(得分:8)

根据MSDN docs

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

来自 INSERT的{​​{1}} 的语法,如:

SELECT

不允许!

我会尝试使用 WHEN NOT MATCHED THEN INSERT itmid SELECT itmid FROM Table3 WHERE id=@id; 进行另一次合并来解决您的问题。

答案 1 :(得分:-2)

这样做

 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);

由于合并插入一次只能插入一个插件,因此多次插入可能会失败。