Update all SQL NULL values in multiple columns using Column level WHERE clause?

前端 未结 4 1845
花落未央
花落未央 2021-01-02 18:31

We have a database with a bunch of wide tables (40-80 columns each) and just found a bug that introduced NULL values into about 500 of the records. The NULL values can appea

相关标签:
4条回答
  • 2021-01-02 19:22

    Since you have to do this all over the place i wrote some javascript to help you build the sql. cut and paste this into your browsers address bar to get your sql.

    javascript:sql='update your table set ';x=0;while(x <= 40){sql += 'answer_'+x+ ' = coalesce(answer_'+x+',99),\n';x++;};alert(sql);
    
    0 讨论(0)
  • 2021-01-02 19:27

    Just poll the sys.columns table for each table and create some dynamic sql... It's brute force but it saves you from having to write all the t-sql out.

    For example:

    DECLARE @TABLENAME AS VARCHAR(255)
    
    SET @TABLENAME = 'ReplaceWithYourTableName'
    
    SELECT 'UPDATE ' + @TableName  + ' SET ' + CAST(Name AS VARCHAR(255)) + ' = 99 
     WHERE ' + CAST(Name AS VARCHAR(255)) + ' IS NULL'
    FROM sys.columns 
    WHERE object_id = OBJECT_ID(@TABLENAME)
        AND system_type_id = 56 -- int's only
    
    0 讨论(0)
  • 2021-01-02 19:27

    I don't like the idea to manipulate the data itself for the purpose of reporting. If you change the NULL values to 99 to just to make your reporting easier then the I consider that data as corrupted. What if there are other consumer apart from reporting which need genuine data?

    I would rather write an intelligent query for the report. For example, if you use ISNULL(columnname, 99), it would return 99 whenever the column value is NULL.

    0 讨论(0)
  • 2021-01-02 19:36

    There isn't any convention to this -- if you want to only process records where respective columns are NULL, you need to use:

    WHERE Answer_1 IS NULL 
       OR Answer_2 IS NULL 
       OR ...
    

    But you could use this in the UPDATE statement:

    UPDATE YOUR_TABLE
       SET col1 = COALESCE(col1, 99),
           col2 = COALESCE(col2, 99),
           col3 = ...
    

    The logic is that the value will be updated to 99 only if the column value is NULL, because of how COALESCE works--returning the first non-NULL value (processing the list provided from left to right).

    0 讨论(0)
提交回复
热议问题