Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change all empty strings to NULL in a table?

Tags:

I have a legacy table with about 100 columns (90% nullable). In those 90 columns I want to remove all empty strings and set them to null. I know I can:

update table set column = NULL where column = ''; update table set column2 = NULL where column2 = ''; 

But that is tedious and error prone. There has to be a way to do this on the whole table?

like image 799
Kyle West Avatar asked Jul 13 '10 14:07

Kyle West


People also ask

How do I replace an empty string to NULL?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.

How do you set all values in a column to NULL?

If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl + 0 .

How do you change the NULL value in a table?

UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.

How do I change all NULL values in SQL?

ISNULL Function in SQL Server To use this function, all you need to do is pass the column name in the first parameter and in the second parameter pass the value with which you want to replace the null value. So, now all the null values are replaced with No Name in the Name column.


1 Answers

UPDATE     TableName SET     column01 = CASE column01 WHEN '' THEN NULL ELSE column01 END,     column02 = CASE column02 WHEN '' THEN NULL ELSE column02 END,     column03 = CASE column03 WHEN '' THEN NULL ELSE column03 END,     ...,     column99 = CASE column99 WHEN '' THEN NULL ELSE column99 END 

This is still doing it manually, but is slightly less painful than what you have because it doesn't require you to send a query for each and every column. Unless you want to go to the trouble of scripting it, you will have to put up with a certain amount of pain when doing something like this.

Edit: Added the ENDs

like image 177
Hammerite Avatar answered Oct 24 '22 07:10

Hammerite