2013-07-11 62 views
1

我有一個簡單的更新陳述。sql server 2008,需要幫助寫條件更新語句

Update tbABC 
Set salary = 1000, name = 'mike' 
Where Id = 1 

我需要在更新工資時添加一個條件,如果工資= 0,則更改爲1000,否則工資不會變。

我做了我的研究,發現了一個類似的問題。 using a conditional update statement in sql

Update tbABC 
Set salary = CASE WHEN (salary = 0) then 1000 ELSE ??????? END, 
    name = 'mike' 
Where Id = 1 

我就死在那????部分。現在可以肯定要把薪水=薪水放在那裏。

+3

你已經完成了,但你沒有意識到它。只需把「工資」放在那裏。然後它會將值更新爲與之前相同的值。 *(如你所說,「薪水=薪水」)* – MatBailie

回答

2

除非絕對必要,我可能會更喜歡使用WHERE子句,而不是一個複雜的CASE功能。簡化,這將給:

update tbABC set salary=1000, name='mike' -- using condition for both field updates 
where Id=1 and salary=0; 

或者對交易保持準確的邏輯:

update tbABC set salary=1000  -- by ID & only if second condition met 
where Id=1 and salary=0; 

update tbABC set name='mike'  -- by ID. 
where Id=1; 

我真的不相信有一個真實世界的情況下無條件地更新員工的姓名,但有一些條件在他的薪金更新。

2

這應該工作

Update tbABC 
Set salary = CASE WHEN (salary = 0) then 1000 ELSE salary END, 
name = 'mike' 
Where Id = 1