在范围内更新

Upsert on a range

我知道这个:

IF EXISTS (SELECT * FROM table WHERE pk = @pk)
BEGIN
   --Update
END
ELSE
BEGIN 
   --INSERT
END

但这适用于一行。假设我有一个 table min_max M 和一个临时 table __MinMaxImport T。我想 INSERT 从 T 到 M,但是 UPDATEbranch_no/product 对已经存在于 M.

插入:

INSERT INTO min_max
    (user_no, branch_no, product, min_stock, max_stock)
SELECT
    @user_no, _branch_no, _product, _min_stock, _max_stock
FROM 
    traxs_temp..__MinMaxImport 
WHERE 
    session_id = @session_id

更新:

UPDATE min_max SET
    date_time = GETDATE(),
    user_no = @user_no,
    min_stock = _min_stock,
    max_stock = _max_stock
FROM
    min_max M
    INNER JOIN traxs_temp..__MinMaxImport T ON T._product = M.product 
AND T._branch_no = M.branch_no
WHERE 
    session_id = @session_id

执行此操作的最佳解决方案是什么?我读到了 MERGE,但我不确定如何使用它。

MERGE应该可以吧

MERGE INTO min_max
USING
(
    SELECT
        @user_no AS _user_no, _branch_no, _product, _min_stock, _max_stock
    FROM 
        traxs_temp..__MinMaxImport 
    WHERE 
        session_id = @session_id    
) AS Src
ON
    (min_max.branch_no = Src._branch_no) AND
    (min_max.product = Src._product)
WHEN MATCHED THEN 
UPDATE SET 
    date_time = GETDATE(),
    user_no = Src._user_no,
    min_stock = Src._min_stock,
    max_stock = Src._max_stock
WHEN NOT MATCHED BY TARGET THEN 
INSERT 
    (user_no, branch_no, product, min_stock, max_stock)
VALUES
    (Src._user_no,
    Src._branch_no,
    Src._product,
    Src._min_stock,
    Src._max_stock)
;