SQL Merge Syntax Single table query

Source: Internet
Author: User

--The project needs to use the Merg grammar, so went online to check the data, found that it is a multi-table query, the problem is that I only have a table, so I am puzzled, and then I brainwave, it's done!
--Table name: T_login (Login table)
--field: F_username (username), f_status (login status 0 = logged in)
--Execution requirements: When the user logs on, if the user is present, the modification status is 0, and if it does not exist, add a record
--Define the parameters:
DECLARE @f_userName varchar (20)
Set @f_userName = ' Test '
DECLARE @f_status int
Set @f_status =0
--Syntax format
Merge into T_login as A
--Joint query, at the same time the T_login table as a condition table, need to use the fields are detected, here directly to the field query out use, in fact, single table and multi-table is a meaning, passed in only parameters, not related to the table
Using (select @f_userName f_username) as b--here if there are multiple conditions, you can also use commas to separate them, such as select @f_userName F_username, @f_status f_status
--Judging conditions
On (a.f_username=b.f_username)--if there are more conditions, you can use and add to the following, such as A.f_status=b.f_status
-If there is
When matched then
--Update status
Update Set F_status=0
--If not present
When isn't matched then
--Insert new data
Insert (F_username,f_status)
--The last semicolon must be added, which is the syntax format
Values (b.f_username,0);

SQL Merge Syntax Single table query

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.