我意识到这一点:
IF EXISTS (SELECT * FROM table WHERE pk = @pk)
BEGIN
--Update
END
ELSE
BEGIN
--INSERT
END
但这适用于一行。我们假设我有一个表min_max M
和一个临时表__MinMaxImport T
。我希望从T到M INSERT
,但在{M}中已存在UPDATE
/ branch_no
对时product
。
INSERT:
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
,但我不确定如何使用它。
答案 0 :(得分:2)
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)
;