SQL使用存储过程中的if语句来更新表

时间:2012-10-27 16:42:57

标签: sql stored-procedures if-statement sql-update

我有一个表有两个字段的学生,StudentName和Grade。 我正在尝试编写一个存储过程来更新Grade。如果学生有A,我想将其更改为B.如果他们有B,我想将其更改为A.如果他们有其他任何我想留下它。这是我最好的尝试

create procedure sp_changegrades
if Grade = 'A' update Students set Grade = 'B'

else if Grade = 'B' update Students set Grade = 'A'

3 个答案:

答案 0 :(得分:5)

只需使用CASE

UPDATE Students
SET Grade = 
(
   CASE WHEN Grade = 'A' THEN 'B'
        WHEN Grade = 'B' THEN 'A'
        ELSE Grade     -- "If they have anything else I want to leave it alone."
    END
)

UPDATE Students
SET Grade = 
(
   CASE WHEN Grade = 'A' 
        THEN 'B'
        ELSE 'A'
    END
)
WHERE Grade IN ('A','B')

答案 1 :(得分:0)

你可以写这样的smth。在此解决方案中,您可以在join部分中定义更新规则,然后更新。

create procedure sp_changegrades
as
begin
    update Students set
        Grade = G.Grade_New
    from Students as S
        inner join (values
            ('A', 'B'),
            ('B', 'A')
        ) as G(Grade_Old, Grade_New) on G.Grade_Old = S.Grade 
end

或者您可以使用case

create procedure sp_changegrades
as
begin
    update Students set
        Grade = 
           case Grade
               when 'A' then 'B'
               when 'B' then 'A'
               else Grade
           end
end

答案 2 :(得分:0)

您可以使用Case语句,并添加where子句,以便只更新相关性行。

UPDATE Students
SET Grade = 
(
   CASE WHEN Grade = 'A' THEN 'B'
        WHEN Grade = 'B' THEN 'A'
        ELSE Grade     -- "Included for Completeness, should never be utilized."
    END
)
WHERE Grade in ('A','B')