title: SQL syntax for checking to see if an INSERT was successful?
body: <p>I'm working on a school assignment that wants me to insert some new values into a database table and then print a message based on whether or not the INSERT was successful. </p>
  
  <p>The question goes like this: </p>
  
  <blockquote>
    <p>Write a script that attempts to insert a new category named “Guitars”
    into the Categories table. If the insert is successful, the script
    should display this message: SUCCESS: Record was inserted.</p>
    
    <p>If the update is unsuccessful, the script should display a message
    something like this: FAILURE: Record was not inserted. Error 2627:
    Violation of UNIQUE KEY constraint 'UQ_<em>Categori</em>_8517B2E0A87CE853'.
    Cannot insert duplicate key in object 'dbo.Categories'. The duplicate
    key value is (Guitars).</p>
  </blockquote>
  
  <p>Currently, this Categories table consists of 2 columns: CategoryID and Category name. It's populated with the values</p>
  
  <pre><code>1     Guitars
  2     Basses
  3     Drums
  4     Keyboards 
  </code></pre>
  
  <p>Obviously the Guitars category that the question wants you to insert is already there, so I'm guessing the whole point of the question is to get it to print the error message. The logic of the question seems fairly straightforward; insert the Guitars category into the table. If the insert was successful, print such-and-such. If it was unsuccessful, print so-and-so. I'm just not sure about the syntax. Here's the SQL code I've got so far:</p>
  
  <pre><code>USE MyGuitarShop;
  
  INSERT INTO Categories (CategoryID, CategoryName)
  VALUES (5, 'Guitars')
  
  IF (          ) --insert is successful
      PRINT 'SUCCESS: Record was inserted'
  ELSE --if insert is unsuccessful
      PRINT 'FAILURE: Record was not inserted.'
      PRINT 'Error 2627: Violation of UNIQUE KEY constraint 'UQ__Categori__8517B2E0A87CE853'.' 
      PRINT 'Cannot insert duplicate key in object 'dbo.Categories'. The duplicate key value is (Guitars).'
  </code></pre>
  
  <p>I feel like there'd be some sort of boolean equation in that IF statement (IF INSERT = success, IF success = TRUE, etc.) but I'm just not sure how to write it. Am I on the right track?</p>
  
  <p>EDIT: I should mention I'm using SQL Server 2012</p>