I have SQL table that has a large number of columns. For some reason, some columns have empty cells instead of NULL cells. I would like to make all empty cells in all the column
I actually use Robert N's answer above daily when I'm importing flat file data sets, so I put it into a stored procedure that I could pass a table name to. It just populates a temp table with the update statements, then executes each row in the table.
USE [master]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: LikeableBias
-- Create date: 2016-06-27
-- Description: Finds and NULLs all blank values in table where column allows nulls
-- =============================================
CREATE PROCEDURE [dbo].[sproc_NullBlanks]
@tablename NVARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
--------Insert update statements to temp table for execution
DECLARE @statements TABLE (statement NVARCHAR(MAX))
INSERT INTO @statements
( statement )
SELECT ('UPDATE '+@tablename+' SET [' + name + '] = NULL WHERE ' + name + ' = '''';')
FROM syscolumns
WHERE id = OBJECT_ID(@tablename)
AND isnullable = 1;
--------Open cursor, execute statements, then close cursor
DECLARE @statement NVARCHAR(MAX)
DECLARE cur CURSOR LOCAL FOR
SELECT statement FROM @statements
OPEN cur
FETCH NEXT FROM cur INTO @statement
WHILE @@FETCH_STATUS = 0 BEGIN
EXEC sys.sp_executesql @statement
FETCH NEXT FROM cur INTO @statement
END
CLOSE cur
DEALLOCATE cur
END
GO