Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace empty cells with NULL values in large number of columns

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,

like image 605
Mayou Avatar asked Sep 27 '13 17:09

Mayou


2 Answers

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.

like image 187
Robert N Avatar answered Oct 04 '22 10:10

Robert N


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

like image 32
podiluska Avatar answered Oct 04 '22 11:10

podiluska