Search This Blog & Web

Thursday, January 13, 2011

Merge Statement SQL SERVER 2008

    Using Merge Statement we can apply Insert, Update and Delete in a single statement

Following is the example for Merge Statement

; MERGE INTO comments AS PC
USING ( select [CommentID] , [Value] , [Comments] , [CommentTypeId]
from @tCommentsValues) as p
on PC.CommentID = p.CommentiD
WHEN MATCHED THEN
UPDATE SET Comments = p.comments,
DateModified = getdate(),
ModifiedBy = @UserID
WHEN NOT MATCHED BY TARGET THEN
 INSERT(CommentId,Comments,DateCreated,DateModified,Active,Deleted,CommentTypeId)
 VALUES (p.CommentID ,p.Comments ,getdate(),@UserID,1,0,[CommentTypeId])
Post a Comment