Home > SQL Server > Easy SQL If Record Exists, Update It. If Not, Insert It.

Easy SQL If Record Exists, Update It. If Not, Insert It.


Hi

try this example :-

CREATE PROCEDURE dbo.spAddUser 
(    @UserID AS int,
     @FirstName AS varchar(50),
     @LastName AS varchar(50)    
)
AS
     BEGIN
          DECLARE @rc int
            UPDATE [Users]           
     SET FirstName = @FirstName, LastName = @LastName
           WHERE UserID = @UserID    
      /* how many rows were affected? */
         SELECT @rc = @@ROWCOUNT 
           IF @rc = 0 
             BEGIN    
               INSERT INTO [Users]                              
  (FirstName, LastName)                        
  VALUES(@FirstName, LastName)           
  END           
 END

Hope this helps

Good Luck

Advertisements
Categories: SQL Server
  1. August 2, 2009 at 1:09 am

    or,

    IF EXIST (SELECT 0 FROM [Users] WHERE UserID = @UserID) BEGIN
    UPDATE [Users] SET …;
    END ELSE BEGIN
    INSERT INTO [Users]…;
    END;

  2. August 8, 2009 at 8:24 am

    Or
    Set @rc = (select count(*) from users where UserID = @UserID)
    If @rc = 0
    Begin — Insert new Record
    End
    Insert Into Users(……..)
    Values (……..)
    else

    Begin — Update Existing Record
    Update Users
    Set ………
    Where UserID = @UserID
    End

  3. yasserzaid
    August 11, 2009 at 6:29 am

    Thanks both sergeos and Night Coder for your comments

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: