简体   繁体   中英

Check if record exists with multiple conditions else insert in a SQL Server stored procedure

I've written procedure as below to check for the record of day and slot combination with teacher or classroom or (specific standard and Division) as below.

ALTER PROCEDURE [dbo].[procCreateSchedule]
    (@classId INT, 
     @dayId INT, 
     @slotId INT, 
     @standardId INT, 
     @divisionId INT, 
     @subjectId INT, 
     @teacherId INT)
AS
BEGIN
    IF NOT EXISTS (SELECT * FROM schedules_test
                   WHERE day = @dayId
                     AND slot = @slotId
                     AND standard = @standardId
                     AND division = @divisionId) 
    ELSE
       IF NOT EXISTS (SELECT * FROM schedules_test
                      WHERE day = @dayId
                        AND slot = @slotId
                        AND teacherId = @teacherId)
       ELSE
          IF NOT EXISTS (SELECT * FROM schedules_test
                         WHERE day = @dayId
                           AND slot = @slotId
                           AND classroom = @classId)
          ELSE
          BEGIN
              INSERT INTO schedules_test (classroom, day, slot, standard, division, subject, teacherId) 
              VALUES (@classId, @dayId, @slotId, @standardId, @divisionId, @subjectId, @teacherId)
          END
      END

But it seems it's not working. Please can anyone suggest how can I check multiple conditions before inserting with help of if else or is there any other approach to tackle this issue?

You can turn all your conditions into one WHERE clause in one SELECT statement:

IF EXISTS (
    SELECT * FROM scheduled_tests
    WHERE day=@dayId AND slot=@slotId AND 
          (classroom=@classId  OR teacherId OR standard=@standardId AND division=@divisionId)
)

 ....

But really, if you can, don't write stored procedures. Add this logic to your C# code, it will be a lot easier to maintain by everybody reading the code in the future.

Don't check this at the application layer. You are subject to race conditions -- two different threads inserting the same data. Both can succeed.

Instead, create unique indexes so the database validates the data. The unique indexes should be on:

  • schedules_test(day, slot, standard, division)
  • schedules_test(day, slot, teacherid)
  • schedules_test(day, slot, classid)

(Note: the order of the keys does not matter.)

Then, the body of the stored procedure can use try / catch :

begin try
    insert into schedules_test(classroom, day, slot, standard, division, subject, teacherId) 
        values (@classId, @dayId, @slotId, @standardId, @divisionId, @subjectId, @teacherId);
end try
begin catch
    . . .
end catch;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM