How to make 0 in all column in a specific table where value is null using MSSQL

Viewed 111

Let the table name is "MyTable"

My current data looks like:

enter image description here

Following, I need after a query on above table:

enter image description here

Actually I need to update all column where value is "NULL", in a single query.

5 Answers

Use ISNULL if you want to see the NULL as 0. Like this

SELECT ISNULL(Column1,0) FROM YourTable

or what you need is to update the value as 0 if NULL and keep the value as it is otherwise. these use a case in the update statement. Like this

Update YourTable
SET Column1 = CASE WHEN Column1 IS NULL THEN 0 ELSE Column1 END,
Column2 = CASE WHEN Column2 IS NULL THEN 0 ELSE Column2 END

and so on for the rest of the columns. Or this is also possible

Update YourTable
    SET Column1 = ISNULL(Column1,0),
cOLUMN2 = ISNULL(Column2,0)

Update table Set column1 = coalesce (column1,0), ....

You can use something like this. It is elegant, but it will update all columns in the table. Huge tables might kill the server

DECLARE @TableName sysname = 'tablename'
Declare @UptQuery varchar(max)

Select @UptQuery = stuff(T.X.query('name').value('.', 'varchar(max)'), 1, 1, '')
from 
(Select ','+name + '=ISNULL('+name+', 0)' name from
    sys.columns where object_id = object_id(@TableName) for xml path(''), type) T(X)

exec ('Update ' + @TableName + ' set ' + @UptQuery)

Old answer It will go through all columns for a table and update everything with 0 if it is null. It is a lot of updates, and I think it is still better to design the table correctly from the start.

DECLARE @TableName sysname = 'tablename'
Declare @ColName sysname

Select name into #temp from sys.columns where object_id = object_id(@TableName)
while(0 < (Select count(1) from  #temp))
BEGIN
  SET ROWCOUNT 1
  Select @ColName = name from #temp
  SET ROWCOUNT 0
  exec('Update ' + @TableName + ' set ' + @ColName + ' = ISNULL('+@ColName+', 0) where ' + @ColName + ' is null')
  delete #temp where name = @ColName
END
   declare @tableName varchar(30)
    set @tableName='MyTable'

    DECLARE @MakeString AS NVARCHAR(MAX)
    SELECT @MakeString= 
    (SELECT cname + ',' AS 'data()' 
    FROM ( select  COLUMN_NAME +'= isnull(['+COLUMN_NAME+'],0)' as cname from INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = @tableName
                )  as ccc
    FOR XML PATH('')) 

    SET @MakeString = LEFT(@MakeString, LEN(@MakeString) - 1)

    DECLARE @Sql AS NVARCHAR(MAX)
    set @Sql='Update '+@tableName+'
    SET '+@MakeString+''

    EXEC(@Sql);

UPDATE Table SET ColumnName1=0 WHERE ColumnName1 IS NULL

...

Related