SQL replace all NULLs

后端 未结 9 535
醉酒成梦
醉酒成梦 2020-12-09 11:34

I have a big table with some NULLs in it. What is the easiest possible way to select from the table with 0\'s instead of NULLs.

Or if there is no easy way to do that

相关标签:
9条回答
  • 2020-12-09 11:46

    You have to manually specify each column in SELECT statement and use ISNULL() function:

    SELECT ISNULL(columnName, 0), ... yes all of them
    
    0 讨论(0)
  • 2020-12-09 11:46

    Be a boss. Write something like:

    select 'update ' + table_name + ' set [' + column_name + '] = '''' where [' + column_name + '] is null'
    from tempdb.information_schema.columns
    where table_name = 'YourTableName'
    

    It'll spit out a big ol' query for you.

    0 讨论(0)
  • 2020-12-09 11:47

    It's not easy to do it without going through each column just as you said.

    NULL has a special and distinct meaning to 0. It means there is no value or unknown as opposed to a known zero value. Some database purists would argue that a row in a table shouldn't have NULLs in at all!

    If the NULLs in your source table really mean zero then change them, otherwise deal with the nulls as they propogate through your queries.

    0 讨论(0)
  • 2020-12-09 11:48

    Alternatively to ISNULL, you can use COALESCE, which is ANSI SQL compatible.

    select coalesce(yourcolumn, 0)
    

    There is lots of columns, I don't want to have to go through each one with something like ISNULL(FieldName,0) AS FieldName.

    You can't always get what you want. Too bad. This is the way to go: column by column.

    0 讨论(0)
  • 2020-12-09 11:59

    As many here have said, the best approach is ISNULL(), however if you want an easy way to generate all those ISNULL()'s use the following code:

    SELECT 'ISNULL([' + COLUMN_NAME + '], ' + 
      CASE 
        WHEN DATA_TYPE = 'bit' THEN '0'
        WHEN DATA_TYPE = 'int' THEN '0'
        WHEN DATA_TYPE = 'decimal' THEN '0'
        WHEN DATA_TYPE = 'date' THEN '''1/1/1900'''
        WHEN DATA_TYPE = 'datetime' THEN '''1/1/1900'''
        WHEN DATA_TYPE = 'uniqueidentifier' THEN '00000000-0000-0000-0000-000000000000'
        ELSE '''''' -- everything else get's an empty string
      END + ') AS [' + COLUMN_NAME + '],'
    FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TableName'
    

    This will make the tedious job a whole lot easier, you then just have to edit the output to account for the various field types (int, varchar, dates, etc)

    Edit: accounting for various datatypes with default values..

    0 讨论(0)
  • 2020-12-09 12:03

    I don't want to have to go through each one with something like ISNULL(FieldName,0) AS FieldName.

    Take the hit and do this once for each one:

    ALTER TABLE TableName ALTER COLUMN FieldName INTEGER DEFAULT 0 NOT NULL;
    

    You can then forget all about ISNULL, COALESCE, three-valued logic, etc.

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