SQLite仅在值不为空时更新列

Fos*_*tah 4 database sqlite

查询: UPDATE item_table SET field1=field1_spanish, field2=field2_spanish;

问:我如何更新field1field1_spanish ONLY,如果 field1_spanish不是空的?我想更新field2field2_spanish如果还field2_spanish没有空.

谢谢!

Jak*_*sel 10

http://sqlfiddle.com/#!5/58554/1

update
  item_table
set
  field1 = coalesce(field1_spanish, field1),
  field2 = coalesce(field2_spanish, field2)
Run Code Online (Sandbox Code Playgroud)

coalesce()函数将返回传递给它的第一个参数,该参数不为null.所以在这种情况下,由于field2_spanish为null,它将field2设置为field2(基本上什么都不做).

要支持空字符串和NULL值,请尝试以下操作:http: //sqlfiddle.com/#!5/b344f/3

update
  item_table
set
  field1 = case when coalesce(field1_spanish, '') = '' then
            field1
           else
            field1_spanish
           end,
  field2 =  case when coalesce(field2_spanish, '') = '' then
            field2
           else
            field2_spanish
           end
Run Code Online (Sandbox Code Playgroud)

  • BTW - sqlfiddle.com是我的网站 (6认同)
  • 好吧,空字符串与null不同.你将不得不做这样的事情:http://sqlfiddle.com/#!5/b344f/3 (3认同)