更新包含列条件的记录

时间:2012-12-21 06:51:16

标签: sql sql-server sql-server-2008 sql-server-2005

我想更新name,appid中匹配table1的记录id。下面的语句将使用以下语句

更新table1值
update table1 set name=@name,appid=@appid where id=@id

我还想要一个条件。更新此id的所有记录,但如果appid,则(@appid is null or id=54)不应更新。如何在一列(appid)上设置限制(条件)。或者我应该写另一个更新声明?我可以格式化上面的查询。请帮忙

3 个答案:

答案 0 :(得分:1)

update table1 set
    name = @name,
    appid = (case when @appid is null or id=54 then appid else @appid end)
where id=@id

答案 1 :(得分:0)

这对你有帮助吗?

update
  table1 
set name=@name,
  appid=ISNUL(@appid, appid) 
where 
  id=(CASE WHEN @id=54 THEN id+1 ELSE @id END)

答案 2 :(得分:0)

update table1 set name=@name,
appid= Case when id=54 then appid else Coalesce(@appid,appid) end where id=@id