我在尝试在存储过程中在SQL中设置变量时遇到问题。我正在检查记录是否设置为活动,并且想法是将其设置为非活动状态,反之亦然。
不可否认,我不是最好的SQL,并且已经尝试过CASE语句和我的例子,但是没有工作......
有人能告诉我我缺少的东西吗?
感谢!!!
ALTER Procedure [dbo].[spAlterStatus]
@CID as int,
@Active varchar(10)
AS
select @Active = Active from Course where
CID = @CID;
if @Active='0' set @Active = '1';
if @Active='1' set @Active = '0';
UPDATE Course
SET Active = @Active WHERE CourseID = @CourseID
答案 0 :(得分:3)
我不确定为什么每个人都在选择和更新 - 你可以在一个操作中完成所有操作:
ALTER Procedure [dbo].[spAlterStatus]
@CID as int
AS
UPDATE Course
SET Active = CASE WHEN Active = '0' THEN '1' ELSE '0' END
WHERE CourseID = @CID
答案 1 :(得分:2)
这是一个问题:
if @Active='0' set @Active = '1';
if @Active='1' set @Active = '0';
这两个语句一个接一个地执行:所以@Active总是最终为'0'。
尝试这样的事情:
if @Active='0' set @Active = '1';
else set @Active = '0';
答案 2 :(得分:1)
这应该有效,也许您必须重命名CID / CourseID。我认为应该是同一个领域。
ALTER Procedure [dbo].[spAlterStatus]
@CID as int,
@Active varchar(10)
AS
select @Active = CASE Active WHEN '0' THEN '1' ELSE '0' END AS Act from Course where
CID = @CID;
UPDATE Course
SET Active = @Active WHERE CID = @CID
答案 3 :(得分:0)
我不是100%确定你想做什么,但这样做会更好:
ALTER Procedure [dbo].[spAlterStatus]
(
@CID int,
@Active varchar(10)
)
AS
SET @Active = (select Active from Course where CID = @CID)
if @Active= '0'
BEGIN
set @Active = '1';
END
ELSE IF @Active= '1'
BEGIN
set @Active = '0';
END
UPDATE Course
SET Active = @Active
WHERE CourseID = @CID