简体   繁体   中英

Can I update a record if it exists, and insert it if not, for multiple rows in a single query in SQL Server?

For example we have this query in MySQL. Is there any way to write it in SQL Server?

INSERT INTO data (name, age, since, description) VALUES
     ("Bob", 23, "01-01-1980", "friend"),
     ("Bill", 33, "03-01-1980", "tall"),
     ("Jane", 43, "12-01-1980", "thin")
 ON DUPLICATE KEY UPDATE age=VALUES(age),
                         since=VALUES(since),
                         description=VALUES(description);

MERGE and IF Exists only work for single row insertion I think.

In SQL Server, you can use MERGE :

merge data as target
    using (select v.*
           from (values ('Bob', 23, '1980-01-01', 'friend'),
                        ('Bill', 33, '1980-03-01', 'tall'),
                        ('Jane', 43, '1980-12-01', 'thin')
                ) v(name, age, since, description)
          ) as source
    on target.name = source.name
when matched
    update set age = source.age,
               since = source.since,
               description = source.description
where not matched then
    insert (name, age, since, description)
        values (source.name, source.age, source.since, source.description);

Note that you should always use single quotes for strings in all databases. That is the SQL standard.

I also fixed the format of what looks like a date to be the standard YYYY-MM-DD format. SQL Server actually prefers YYYYMMDD, but I like the hyphens (because they are ISO 8601 standard and more accepted across databases) and they almost always work in SQL Server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM