Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Whats wrong with this update statement

Author  Topic 

mary_itohan
Posting Yak Master

191 Posts

Posted - 2008-09-23 : 13:54:40
Hello,
Am working on a billing system and guarding against negative billing.

What is wrong with this


--update table
if ((update tbl_credits set credits = (credits - @billing) where username = @user) < 0)
-- if results are less than 0. ie negative. Update to 0
begin
update tbl_credits set credits = 0 where username = @user
end





I get this error

Msg 102, Level 15, State 1, Procedure My_billing, Line 209
Incorrect syntax near 'tbl_credits'.













_____________________


Yes O !

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-09-23 : 14:03:13
what you want is this

update tbl_credits 
set credits = case when (credits - @billing)<0 then 0 else (credits - @billing) end
where username = @user
Go to Top of Page

mary_itohan
Posting Yak Master

191 Posts

Posted - 2008-09-23 : 14:25:33
Cool. Thanks

Is it possible to get the value of the previous credits during the transaction ? ie

Merge the two codes below into one ???


set @present_credits = (select credits from tbl_credits where username = @user)

update tbl_credits
set credits = case when (credits - @billing)<0 then 0 else (credits - @billing) end
where username = @user


_____________________


Yes O !
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-09-23 : 14:28:58
yup you can

update tbl_credits 
set credits = case when (credits - @billing)<0 then 0 else (credits - @billing) end,
@present_credits =credits
where username = @user
Go to Top of Page

mary_itohan
Posting Yak Master

191 Posts

Posted - 2008-09-23 : 15:52:00
great.

Thanks

_____________________


Yes O !
Go to Top of Page

mary_itohan
Posting Yak Master

191 Posts

Posted - 2008-09-23 : 18:17:12
One last question.

Is it possible to assign the credits after this transaction to a variable ? Or i have to run a seperate select command ie

update tbl_credits
set credits = case when (credits - @billing)<0 then 0 else (credits - @billing) end,
@present_credits =credits
where username = @user

set @credits_after = (select credits from tbl_credits where username = @user)

_____________________


Yes O !
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-09-24 : 01:41:23
try like this

update tbl_credits 
set @credits_after =credits = case when (credits - @billing)<0 then 0 else (credits - @billing) end,
@present_credits =credits
where username = @user
Go to Top of Page
   

- Advertisement -