Sql query for updating database if value is not null?

后端 未结 2 1346
长情又很酷
长情又很酷 2021-02-03 20:26

I am having a table which has about 17 fields. I need to perform frequent updates in this table. But the issue is each time I may be updating only a few fields.

相关标签:
2条回答
  • 2021-02-03 20:37

    Without knowing your database it's tough to be specific. In SQL Server the syntax would be something like ...

    UPDATE MyTable 
    SET 
            Field1 = IsNull(@Field1, Field1),
            Field2 = IsNull(@Field2, Field2),
            Field3 = IsNull(@Field3, Field3)
    WHERE 
         <your criteria here>
    

    EDIT

    Since you specified SQLLite ...replace my IsNull function with COALESCE() or alternately look at the IfNull function.

    0 讨论(0)
  • 2021-02-03 20:40

    Posting a SQL Server solution with 2 tables for posterity. Query joins two tables and updates the values that are present. Otherwise original value is maintained.

    tables = table1, table2 each having field1 and field2

    update t1 WITH (ROWLOCK)
    set T1.Field2 = ISNULL(T2.Field2,T1.Field2)
    from Table1 T1 Join Table2 T2 
        ON T1.Field1 = T2.Field1
    
    0 讨论(0)
提交回复
热议问题