views:

115

answers:

5

I am using sql server. I have a table and the columns on this table contains empty spaces for some records. Now i need to move the data to another table and replace the empty spaces with NULL value. I tried to use

REPLACE(ltrim(rtrim(col1)),' ',NULL)

but it doesn't work. Because it will convert all the value of col1 to NULL. I just need to convert only those values that have empty spaces to NULL.

Thank you in advance for your help.

+3  A: 

Maybe something like this?

UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0
Developer Art
+5  A: 

Did you try this?

UPDATE table 
SET col1 = NULL 
WHERE col1 = ''

As the commenters point out, you don't have to do ltrim() or rtrim(), and NULL columns will not match ''.

egrunin
@Martin Smith: I was wrong. Edit appended.
egrunin
You don't even need to use RTRIM. SQL Server ignores trailing whitespace when comparing strings.
Bennor McCarthy
@Bennor McCarthy: wow, I'm really slipping...going to drop that clause now
egrunin
Not really a major problem. It's not like performance or use of indexes is really a concern for the query. Your answer was still correct anyway. :)
Bennor McCarthy
A: 

A case statement should do the trick when selecting from your source table:

CASE
  WHEN col1 = ' ' THEN NULL
  ELSE col1
END col1

Also, one thing to note is that your LTRIM and RTRIM reduce the value from a space (' ') to blank (''). If you need to remove white space, then the case statement should be modified appropriately:

CASE
  WHEN LTRIM(RTRIM(col1)) = '' THEN NULL
  ELSE LTRIM(RTRIM(col1))
END col1
craigh2
A: 

here's a regex one for ya.

update table
set col1=null
where col1 not like '%[a-z,0-9]%'

essentially finds any columns that dont have letters or numbers in them and sets it to null. might have to update if you have columns with just special characters.

DForck42
A: 

SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update

UPDATE table
SET col1 = NULL
WHERE col1 = ''

NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.

If you want to do it during your copy from one table to another, use this:

INSERT INTO newtable ( col1, othercolumn )
SELECT
   NULLIF(col1, ''),
   othercolumn
FROM table
Bennor McCarthy