SQL replace all NULLs

后端 未结 9 536
醉酒成梦
醉酒成梦 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 12:06

    I wanted a dynamic query to do the update option. Borrowing from the post above and another I have the following:

                USE [YOUR DATABASE] 
                DECLARE @tableName nvarchar(100) 
                DECLARE @name varchar(50) 
                DECLARE @dtype varchar(50) 
                DECLARE @CMD NVARCHAR (200) 
    
                SET @tableName = [YOUR TABLE NAME] 
    
    
                DECLARE db_cursor CURSOR FOR 
    
                      SELECT c.name, t.name AS Dtype 
                      FROM sys.columns c 
                      INNER JOIN sys.types t 
                      ON t.system_type_id = c.system_type_id 
                      WHERE c.[object_id] = 
                          (SELECT [object_id] FROM sys.objects WHERE type = 'U' AND [NAME] = @tableName) 
    
                OPEN db_cursor 
                FETCH NEXT FROM db_cursor INTO @name, @Dtype 
    
                WHILE @@FETCH_STATUS = 0 BEGIN
    
                SET @CMD = 'UPDATE ' + @tableName + ' SET ' + quotename(@name) +' = ' + 
    
                   (CASE 
                     WHEN (@Dtype = 'bit') THEN '0' 
                     WHEN (@Dtype = 'int') THEN '0' 
                     WHEN (@Dtype = 'decimal') THEN '0' 
                     WHEN (@Dtype = 'date') THEN '''1/1/1900''' 
                     WHEN (@Dtype = 'datetime') THEN '''1/1/1900'''
                     WHEN (@Dtype = 'uniqueidentifier') THEN '00000000-0000-0000-0000-000000000000' 
                  ELSE '''''' 
                  END ) 
                + ' WHERE ' + quotename(@name) +' IS NULL' 
    
                PRINT @CMD 
    
                EXEC sp_executeSQL @cmd 
    
                FETCH NEXT FROM db_cursor INTO @name, @Dtype 
    
                END 
    
                CLOSE db_cursor 
                DEALLOCATE db_cursor
    
    0 讨论(0)
  • 2020-12-09 12:07

    You have two options really

    ISNULL(yourColumn,0) AS columnName
    

    or to actually fix the issue and change all the NULL data to 0

    UPDATE table
    SET column = 0
    WHERE
    column IS NULL    -- remember "column = NULL" always equates to NULL!
    

    When you do this dont forget the WHERE or everything will end up being 0!

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

    Despite your reluctance to do so,

    ISNULL(FieldName,0) AS FieldName
    

    for each column is the correct way to handle this.

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