Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the merge command

Say I have a table called Employee (has ID, NAME, ADDRESS, and PHONE columns). (Not my real problem, but simplified to make the question easier.)

If I call a sproc called UpdateEmployee and I pass in a @Name, @Address, @Phone and @ID.

Can merge be used to easily check to see if the ID exists? If it does to update the name, address and phone? and if it does not to insert them?

I see examples on the net, but they are huge and hairy. I would like a nice simple example if possible.

(We recently upgraded to SQL 2008, so I am new to the merge command.)

like image 217
Vaccano Avatar asked Jun 16 '10 20:06

Vaccano


People also ask

What is the use of merge command?

Use the MERGE statement to select rows from one or more sources for update or insertion into a table or view. You can specify conditions to determine whether to update or insert into the target table or view. This statement is a convenient way to combine multiple operations.

How do I run a git merge?

To merge branches locally, use git checkout to switch to the branch you want to merge into. This branch is typically the main branch. Next, use git merge and specify the name of the other branch to bring into this branch. This example merges the jeff/feature1 branch into the main branch.

How do you do merge?

Merge cellsClick the first cell and press Shift while you click the last cell in the range you want to merge. Important: Make sure only one of the cells in the range has data. Click Home > Merge & Center.


1 Answers

Bill Karwin's code is almost correct. I made the needed changes. Playing with the variable values will allow you to see it in action. Table:

CREATE TABLE [dbo].[employee](
    [ID] [int] NULL,
    [Name] [char](20) NULL,
    [Address] [char](20) NULL,
    [Phone] [int] NULL
) ON [PRIMARY]

Code:

DECLARE @ID int, @NAME char(20), @ADDRESS char(20), @PHONE int
SET @ID=2
SET @NAME='Jenny'
SET @ADDRESS='11 My St'
SET @PHONE=228326

MERGE Employee AS target
USING (SELECT @ID, @NAME, @ADDRESS, @PHONE) AS source (ID, Name, Address, Phone)
ON (target.ID = source.ID)
WHEN MATCHED THEN
  UPDATE SET NAME    = source.Name,
             ADDRESS = source.Address,
             PHONE   = source.Phone
WHEN NOT MATCHED THEN
  INSERT (ID, NAME, ADDRESS, PHONE) 
  VALUES (source.ID, source.Name, source.Address, source.Phone);
like image 132
Kenneth Avatar answered Sep 30 '22 01:09

Kenneth