Login    
 
 
 
 
Text/HTML
  
You are here :: Blogs Saturday, May 19, 2012

Search
Note: This uses the internal blog search engine. The Google search engine is also available at the top of the page.
  
Disclaimer

Please review the site disclaimer before downloading or using content found on this site

  
Categories
  
DEVSHED Blog
As always, I welcome your comments!
Nov 4

Written by: Steve Gray
11/4/2010 10:05 AM  RssIcon

I’ve just written my first SQL MERGE statement, and I’m guessing that I’ll need to keep an example around for a while until I get the hang of it. It seems pretty useful.

This first example is a simple one, I imagine that most of them will look something like this.

I needed to see if any of the fields had changed before issuing the update, so that I wouldn’t call the UPDATE clause unnecessarily. I also added the new OUTPUT clause (very cool)

 

-- Drop stored procedure if it already exists
IF EXISTS (
  SELECT * 
    FROM INFORMATION_SCHEMA.ROUTINES 
   WHERE SPECIFIC_SCHEMA = N'dbo'
     AND SPECIFIC_NAME = N'sp_EmployeeMaster_MERGE' 
)
   DROP PROCEDURE dbo.sp_EmployeeMaster_MERGE
GO
 
CREATE PROCEDURE dbo.sp_EmployeeMaster_MERGE
 
@FileNumber int,  
@LastName varchar(25),  
@FirstName varchar(25),  
@PositionNumber int  ,
@UserID varchar(255)
 
AS
 
MERGE EmployeeMaster AS t
    USING (SELECT @filenumber as filenumber, @lastname as lastname, 
@firstname as firstname, @positionnumber as positionnumber ) AS s
        ON (t.filenumber = s.filenumber)
    WHEN MATCHED AND (t.firstname <> s.firstname or t.lastname <> s.lastname 
or t.positionnumber <> s.positionnumber)
        THEN UPDATE SET t.firstname = s.firstname , t.lastname = s.lastname , 
t.positionnumber = s.positionnumber,
                    t.ModifiedDateTime = GETDATE(),
                    t.ModifiedUser = @UserID
    when not matched then
        INSERT      (FileNumber  ,LastName  ,FirstName  ,PositionNumber , modifiedUser)  
            VALUES  (@FileNumber ,@LastName ,@FirstName ,@PositionNumber, @UserID) 
     OUTPUT $action, Inserted.*, deleted.*;
 
 
GO
 
grant exec on sp_EmployeeMaster_MERGE to public

Tags:
Categories:
Location: Blogs Parent Separator DEVSHED Blogs Child Separator SQL
As always, I welcome your comments!
  
 
 
Home | Products | Blogs | Contact Us | Links | God's Plan
Privacy Statement | Terms Of Use
 
Copyright 2011 by Devshed.us