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
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
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!
Despite your reluctance to do so,
ISNULL(FieldName,0) AS FieldName
for each column is the correct way to handle this.