I am 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 the INSERT was successful.
The question will be like this:
Write a script that tries to insert a new category called "Guitars" into the category table. If the tab is successful, the script should display this message: SUCCESS: A record has been inserted.
If the update is unsuccessful, the script should display a message something like this: FAILURE: The record was not inserted. Error 2627: Violation of UNIQUE KEY constraint 'UQ_Categori_8517B2E0A87CE853'. Cannot insert duplicate key in object "dbo.Categories". Duplicate key value (guitar).
Currently, the table of these categories consists of 2 columns: CategoryID and Category name. It is populated with values
1 Guitars
2 Basses
3 Drums
4 Keyboards
Obviously, the category of guitars that you want to insert in the question already exists, so I assume that the whole point of the question is to get it to print an error message. The logic of the question seems pretty simple; insert the category of guitars into the table. If the insert was successful, print one. If this was unsuccessful, type so-so and so. I'm just not sure about the syntax. Here is the SQL code that I still have:
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).'
I feel that there will be some kind of Boolean equation in this IF expression (IF INSERT = success, IF success = TRUE, etc.), but I'm just not sure how to write it. Am I on the right track?
EDIT: I have to mention that I am using SQL Server 2012