Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSSQL INSERT OR UPDATE if EXISTS

Need to insert a row if its not exist and update if exists. I've found this solution for MySQL:

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

name="A", age=19

But I can't find similar for MSSQL..

like image 235
Dmytro Avatar asked Feb 21 '19 09:02

Dmytro


People also ask

Can I use if exists in SQL?

It works fine if the object exists in the database. In case the object does not exist, and you try to drop, you get the following error. To avoid this situation, usually, developers add T-SQL If Exists statement and drop the object if it is already available in the database.

Can we use insert or update in SQL?

INSERT OR UPDATE table query inserts or updates rows of data the come from the result set of a SELECT query. The columns in the result set must match the columns in the table. You can use INSERT OR UPDATE with a SELECT to populate a table with existing data extracted from other tables.


2 Answers

You can use 2 statements (INSERT + UPDATE) in the following order. The update won't update anything if it doesn't exist, the insert won't insert if it exist:

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)

Or a 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;
like image 188
EzLo Avatar answered Oct 05 '22 23:10

EzLo


I prefer checking the @@ROWCOUNT. It's a much more compact solution.

UPDATE table set name = 'A', age = 19 WHERE id = 1;
IF @@ROWCOUNT = 0
INSERT INTO table (id, name, age) VALUES(1, "A", 19);
like image 31
Neil B Avatar answered Oct 06 '22 00:10

Neil B