Commands similar to MySQL replace into in MsSQL

Source: Internet
Author: User
Tags sql 2008

In MsSQL, commands similar to MySQL replace into remember a case in which MySQL was used many years ago. At that time, a requirement was raised when an additional item was added to the data table, determine whether the cursor exists. If the cursor is added when the cursor exists, update the token. Remember that at that time, the callback command was executed in the program.

1SELECT id FROM table WHERE id = 1;

 

In the program, determine whether the token has been added.
1insert into `table`(`id`,`value`)values(1,'new value');

 

Vice versa
1update `table` set value='new value' where id = 1;

 

After that, the replace into statement method can be used to compile the above functions only when it comes to MySQL.
1replace into `table`(`id`, `value`) values(1, 'new value');

 

When replace into is used, the data table must have a Primary Key or a Unique Key. Otherwise, replace into will directly add the data to the data table, causing a duplicate. What should I do on SQL Server? Before SQL 2008
1 UPDATE [table] 2 SET [value] = 'new value' 3WHERE [id] = 14 -- determine whether the token has been updated to the data 5if @ rowcount = 0 and @ error = 06 INSERT into [table] ([id], [value]) VALUES (1, 'new value') SQL 2008 (inclusive) later versions: 1 merge into [table] AS [t] USING (SELECT 1 AS [id]) AS [s] ON [t]. [id] = [s]. [id] 2 when matched THEN3 UPDATE4 SET [value] = 'new value' 5 when not matched THEN6 INSERT ([id], [value]) VALUES (1, 'New value ');

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.