MSSQL INSERT或UPDATE如果EXISTS

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

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

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

name =“A”,年龄= 19岁

但我找不到类似的MSSQL ..

sql-server mssql-jdbc
1个回答
6
投票

您可以按以下顺序使用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;
© www.soinside.com 2019 - 2024. All rights reserved.