简体   繁体   中英

IF ELSE statements to update table in sql procedure does not work

I have a table called Employees and need to update the SalaryId of the Employee by 1 if 1 is inputed and decrease it by -1 in case -1 is inputed. I think my approach has totally wrong logic, but I cannot find what I wanna do although I hav been searching for a while. Can someone assist me understand what I am doing wrong?

ALTER PROCEDURE "dba"."updatePosition"(IN rating int, @PersonalID int )
AS BEGIN
   IF rating = 1 
     UPDATE dba.Employees
      IF (dba.Employees.SalaryId  > 1 && dba.Employees.SalaryId < 7)

      SET dba.Employees.SalaryId = dba.Employees.SalaryId  + 1
      WHERE dba.Employees.PersonalID = @PersonalID

   ELSEIF rating = -1
   UPDATE dba.Employees
   SET dba.Employees.SalaryId  = dba.Employees.SalaryId  - 1
        IF dba.Employees.SalaryId  < 1
           dba.Employees.SalaryId  = 1
        IF dba.Employees.SalaryId  > 7
           dba.Employees.SalaryId = 7
        WHERE dba.Employees.PersonalID = @PersonalID
    END

This doesn't make sense to me:

 UPDATE dba.Employees
  IF (dba.Employees.SalaryId  > 1 && dba.Employees.SalaryId < 7)

  SET dba.Employees.SalaryId = dba.Employees.SalaryId  + 1
  WHERE dba.Employees.PersonalID = @PersonalID

Perhaps you want:

UPDATE dba.Employees
  SET dba.Employees.SalaryId = dba.Employees.SalaryId  + 1
  WHERE dba.Employees.PersonalID = @PersonalID AND
        dba.Employees.SalaryId  > 1 AND
        dba.Employees.SalaryId < 7

You're wildly mixing procedural code ( IF ) and SQL code ( UPDATE , WHERE )...

I can imagine you're after something like that:

ALTER PROCEDURE "dba"."updatePosition"(IN @Rating int,
                                       IN @PersonalID int)
AS
BEGIN
  IF abs(@Rating) = 1 THEN
    UPDATE dba.Employees
           SET SalaryId + @Rating
           WHERE PersonalID = @PersonalID
                 AND SalaryId + @Rating >= 1
                 AND SalaryId + @Rating <= 7;
  END IF;
END;

It increases or decreases -- depending on the sign of @Rating -- the SalaryId of the employee identified by @PersonalID by 1 , if that change doesn't cause the SalaryId to drop below 1 or raise above 7 -- the checks for that belong in the WHERE clause an not in IF s spread anywhere in the UPDATE statement. To check that only steps of -1 or 1 are possible, the UPDATE is wrapped in an IF , that is only entered, when the absolute value of @Rating equals 1 . You can also remove the IF , if you want to allow more than 1 step at once.

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