11

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 columns to be NULL.

I know that the way to go for a single column is:

 UPDATE your_table SET column = NULL WHERE column = ''

However, I am not sure how to execute a similar logic efficiently for all columns without having to write the column names one by one.

Thanks,

1
  • 3
    @DanBracuk what fun is that? Learning to do this efficiently now could save untold minutes down the road. Commented Sep 27, 2013 at 17:44

3 Answers 3

27

Run the following query:

SELECT 'UPDATE yourtable SET ' + name + ' = NULL WHERE ' + name + ' = '''';'
FROM syscolumns
WHERE id = object_id('yourtable')
  AND isnullable = 1;

The output of this query will be a chunk of SQL script like this:

UPDATE yourtable SET column1 = NULL WHERE column1 = '';
UPDATE yourtable SET column2 = NULL WHERE column2 = '';
UPDATE yourtable SET column3 = NULL WHERE column3 = '';
-- etc...

Copy and paste that SQL script into a new query and run it to update all your columns.

Sign up to request clarification or add additional context in comments.

5 Comments

That's a neat trick! Thanks! But is there any way I can pass the results of your first query to something that I can run automatically? I am doing this via C#, that's why... Thanks!
Depends how you're doing your db access, but say you're using C# and Linq To SQL, you could do something like this: using (MyDataContext db = new MyDataContext()) { string queryBuilder = "...first query from above..."; var resultsetOfUpdateQueries = db.ExecuteQuery<string>(queryBuilder); foreach (string oneUpdateQuery in resultsetOfUpdateQueries) { db.ExecuteCommand(oneUpdateQuery); } } No worries about SQL injection because the only variable components of the dynamic SQL statement will all be column names from a dictionary table.
Why would you do this, presumably one off task, in c#?
The reason I need to do this is that I have used bulk insert from a csv file to populate my SQL table. For some odd reason, some of the empty cells in the csv file got translated as NULL in the table, while others got translated as empty cells in table. The transformation above is to make all the empty tables unified.
@mayou To execute this in one fell swoop using Robert's code above, see the stored procedure code I posted below (too long to post in this comment). Kudos to Robert N as this has saved me tons of time over the last couple months.
3

You could do a query on syscolumns to get a list of columns, and use the results to construct your query.

select quotename(name) + ' = nullif (' + quotename(name)+ ','''')'
from syscolumns 
where id = object_id('yourtable')

Additionally, if you write your query as

update yourtable
set
    yourcolumn=nullif(yourcolumn, ''),
    yourcolumn2=nullif(yourcolumn2, ''),
    ...    

then you can do it in a single query without a where clause

5 Comments

I would still have to write each column to check for the nullif. That wouldn't be very efficient.
Thanks. I get the first part, but I am not sure how to use the result of the first query to write the second one: i.e. how to pass the column names obtained from the first query to the second query
@Mariam The easy way is to copy the results and paste them into a new query.
An example of how to copy/paste? Come on now.
@Goat Co I meant an example of an automatic passing of the results of the query to the second query. It is quite obvious I wasn't asking for a trivial copy/paste.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.