title: Fast upsert Sql server 2008 R2
body: <p>I'm trying to upsert records using SP into one table.</p>
  
  <pre><code>CREATE TABLE [dbo].[SHARE_AD_GROUP](
      [SHARE_AD_GROUP_ID] [int] IDENTITY(1,1) NOT NULL,
      [SHARE_ID] [int] NOT NULL,
      [AD_GROUP] [varchar](200) NOT NULL,
      [SHARE_PERMISSIONS] [varchar](65) NULL,
  </code></pre>
  
  <p>what is the best way of the following:</p>
  
  <p>1- </p>
  
  <pre><code>ALTER PROCEDURE [dbo].[PROC_INSERT_SHARE_AD_GROUP]
  
  
  @shareID int,
  @ownerId varchar(200),
  @sharePermissions varchar(65)
  
  AS
  
  BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
  
      UPDATE [dbo].SHARE_AD_GROUP
                 SET 
                     [SHARE_PERMISSIONS] = @sharePermissions
               WHERE SHARE_ID = @shareID and [AD_GROUP] = @ownerId
      if @@ROWCOUNT =0 
      begin
      INSERT INTO [dbo].SHARE_AD_GROUP
                         (SHARE_ID,[AD_GROUP],[SHARE_PERMISSIONS])
                   VALUES
                         (@shareID,@ownerId,@sharePermissions)
      end
  
  end
  </code></pre>
  
  <p>2-</p>
  
  <pre><code>   BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
  
      declare @id int
      SET NOCOUNT ON;
      set @id = (select top 1 SHARE_AD_GROUP_ID from SHARE_AD_GROUP where SHARE_ID = @shareID and [AD_GROUP] = @ownerId)
          if @id is null
              begin
                  INSERT INTO [dbo].SHARE_AD_GROUP
                         (SHARE_ID,[AD_GROUP],[SHARE_PERMISSIONS])
                   VALUES
                         (@shareID,@ownerId,@sharePermissions)
                   set @id = SCOPE_IDENTITY()
              end
          else
              begin
              UPDATE [dbo].SHARE_AD_GROUP
                 SET 
                     [SHARE_PERMISSIONS] = @sharePermissions
               WHERE SHARE_ID = @shareID and [AD_GROUP] = @ownerId
              end
  End
  </code></pre>
  
  <p>3- Merge ==> No idea how to write that.</p>
  
  <p>What is the fastest way in your opinion?</p>