将插入与 select 语句合并

问题描述 投票:0回答:3

这对我有用

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;
sql sql-server merge sql-server-2008-r2
3个回答
14
投票

根据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
进行另一次合并来解决您的问题。


0
投票

您希望在

src
语句顶部更好地定义您的
MERGE
表。

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;

根据上述假设

Table3.itemid
是期望值。

您可能希望为

src
定义一个
MERGE
表,其中包含
itemid
中的
Table3
作为返回列的一部分。

您应该为连接

MERGE
Table2
Table3
语句定义一些表变量或 CTE 以满足您的需求。

基于您提供的内容的一个简单示例如下所示。但您的具体需求可能会根据数据模式而有所不同。

WITH source AS ( 
    SELECT TOP 1 t3.itmid, t2.qty, ... [you could use * here but its better to list them out]
    FROM Table2 AS t2 
    INNER JOIN Table3 AS t3
        ON    t3.id = t2.id 
    WHERE t3.id = @id
)
MERGE source AS src...
...
WHEN NOT MATCHED THEN
    INSERT (itmid)
    VALUES src.itmid
;

-5
投票

这样做

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

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

© www.soinside.com 2019 - 2024. All rights reserved.