Using SQL Server 2016, I have a very simple IF NOT Exists ..... INSERT statement
inside a loop. This works well, as expected. Is there a way to identify which records existed therefore did not insert and which records did not exist therefore were inserted without using a second query?
I can easily achieve this by executing a SELECT, then if not found I insert however this is two queries in my loop. I would like to try and achieve this in one query if possible?
The purpose of this is to show the user:
- Chris is now enrolled in English
- Chris is now enrolled in Maths
- Chris was already enrolled in Science
So 1 and 2 did not exist therefore inserted. 3 did exist therefore did not insert
and example of this loop for jon:
for i = 0 to numOfCourses
sql = IF NOT EXISTS (SELECT fieldName from tableName
WHERE courseID = 1 AND directoryID = 2)
BEGIN
INSERT INTO tableName(courseID, directoryID)
VALUES (1, 2)
END
next