MSSQL插入或更新(如果存在)

时间:2019-02-21 09:20:12

标签: sql-server mssql-jdbc

如果不存在则需要插入行,如果存在则需要更新。 我找到了适用于MySQL的解决方案:

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    

name =“ A”,年龄= 19

但是我找不到类似的MSSQL。

2 个答案:

答案 0 :(得分:5)

您可以按以下顺序使用2条语句(INSERT + UPDATE)。如果不存在,则更新不会更新任何内容,如果存在,则插入内容也不会插入:

UPDATE T SET
    name = 'A',
    age = 19
FROM
    [table] AS T
WHERE
    T.id = 1

INSERT INTO [table] (
    id,
    name,
    age)
SELECT
    id = 1,
    name = 'A',
    age = 19
WHERE
    NOT EXISTS (SELECT 'not yet loaded' FROM [table] AS T WHERE T.id = 1)

MERGE

;WITH ValuesToMerge AS
(
    SELECT
        id = 1,
        name = 'A',
        age = 19
)
MERGE INTO 
    [table] AS T
USING
    ValuesToMerge AS V ON (T.id = V.id)
WHEN NOT MATCHED BY TARGET THEN
    INSERT (
        id,
        name,
        age)
    VALUES (
        V.id,
        V.name,
        V.age)
WHEN MATCHED THEN
    UPDATE SET
        name = V.name,
        age = V.name;

答案 1 :(得分:0)

我更喜欢检查@@ROWCOUNT。这是一个更为紧凑的解决方案。

UPDATE table set name = 'A', age = 19 WHERE id = 1;
IF @@ROWCOUNT = 0
INSERT INTO table (id, name, age) VALUES(1, "A", 19);