SQL Server: Nullify blanks, spaces or 'NULL' strings of all varchar columns of a table

There was a database which had 25 tables and data was not in normalized way. Meaning there were blank spaces or string 'NULL' or a single space or multiple spaces were available in a column as depicted below.


I wanted all of them to be Nullified. Doing each and every table would be a hectic task. I needed some Stored Procedure kind to do it quick. So I developed this.
-------------------------------------------------------------------------------------
-- Created Author : SHIVAKUMAR.U
-- Created date   : 24 Mar 2010
-- Description    : Nullifies Blanks, spaces or text containing NULL
-- Usage          : [UspNullifyBlanks] 'SchemaName','TableName'
------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[UspNullifyBlanks]  @SchemaName varchar(200) ,@TableName varchar(200)
AS
BEGIN

DECLARE @SQL As Varchar(max)
SET @SQL = 'UPDATE [' + @SchemaName + '].[' + @TableName + '] SET '

SELECT @SQL = COALESCE(@SQL + '[', '[') +
              COLUMN_NAME + ']=NULL where (['+COLUMN_NAME+']='+ CHAR(39) + 'NULL' + CHAR(39)+
              ' OR [' + COLUMN_NAME +'] = '''''+ ');' + CHAR(13)+ 'UPDATE [' + @SchemaName + '].[' + @TableName + '] SET '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
    AND DATA_TYPE Like '%char%'

SET  @sql = SUBSTRING(@sql,0,Len(@sql)-CHARINDEX (')' ,REVERSE(@sql))+3)

PRINT @sql -- If required we can use EXEC (@SQL) here to execute directly through SP
END

Copy the result produced and paste in query  editor and Run.

No comments:

Post a Comment