有条件地使用更新语句

时间:2011-12-15 09:32:19

标签: sql-server stored-procedures

我希望在我的位参数的值为1时完成Update语句。如何实现这一目标?

这是我的存储过程:

 CREATE PROCEDURE sp_subBalance @Cost decimal, @userid int, @bit bit output
 AS
    declare @SubbedBalance decimal, @Currbalance decimal

    set @Currbalance = (SELECT User_Balance_tbl.Balance
                        FROM User_Balance_tbl
                        WHERE User_Balance_tbl.UserID = @userid)

    set @SubbedBalance = (select @Currbalance - @cost)

    set @bit = (case when @SubbedBalance > 0 Or @SubbedBalance = 0 then 1 else 0 end) 

    case when @bit = 1 then (update User_Balance_tbl 
                             set Balance = @SubbedBalance  
                             where  User_Balance_tbl.UserID = @userid) 
end

3 个答案:

答案 0 :(得分:0)

If @bit = 1
begin
 Update ...
End

不是case when @bit = 1

答案 1 :(得分:0)

一旦确定您的位变量为1

,是否可以使用If条件
If @SubbedBalance >= 0
         Set @bit = 1
else
     Set @bit = 0

if @bit = 1
begin
   update User_Balance_tbl 
   set Balance = @SubbedBalance    
   where  User_Balance_tbl.UserID = @userid
end

答案 2 :(得分:0)

可以通过以下方式完成:

 CREATE PROCEDURE sp_subBalance @Cost decimal , @userid int
 ,@bit bit output
 AS

 declare @SubbedBalance decimal
 , @Currbalance decimal

 set @Currbalance =
 (
 SELECT User_Balance_tbl.Balance
 FROM User_Balance_tbl
 WHERE User_Balance_tbl.UserID = @userid
 )
 set @SubbedBalance = (select @Currbalance - @cost)
 set @bit =( case when @SubbedBalance>0 Or @SubbedBalance=0  then 1 else 0 end) 

 IF (@bit=1)
   BEGIN
      update User_Balance_tbl set Balance = @SubbedBalance  
        where  User_Balance_tbl.UserID = @userid
   END