我有一个学生表,有两个字段,StudentName 和 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'
我有一个学生表,有两个字段,StudentName 和 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'
只需使用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')
你可以这样写。在此解决方案中,您定义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
您可以使用 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')