da-sztorc
2/15/2018 - 2:19 PM

Bulk Insert/Update Template

Template for bulk inserts/updates with transactions.

BEGIN TRY
  
  BEGIN TRANSACTION

  IF EXISTS (	SELECT TOP 1 NULL
              FROM sys.objects WITH (NOLOCK)
              WHERE object_id = OBJECT_ID(N'[Schema].[Table]')
                AND type in (N'U'))
  BEGIN
  
    IF NOT EXISTS(SELECT TOP 1 NULL
                  FROM [Schema].[Table] WITH (NOLOCK)
                  WHERE [Column] = 'FirstValue')
      BEGIN
      
        INSERT INTO [Schema].[Table] ([Column])
          VALUES  ('FirstValue'),
                  ('SecondValue'),
                  ('ThirdValue');

      END
  END
  
  COMMIT TRANSACTION
  
END TRY

BEGIN CATCH

  IF @@TRANCOUNT > 0
  BEGIN
    ROLLBACK TRANSACTION
  END

END CATCH