6

I have a table that contains NULL values but the problem is that some of the values are actually string "NULL" and not actual NULLS so when you trying something like

where date is null

it will not return the fields that have the "NULL" string.

What I am needing to do is run an update of the whole table that will convert all string "NULLS" to the actual NULL value. The "NULL" strings happen throughout all columns of the table so it is not just 1 column that needs to be updated. I am not sure how to approach this scenario. I'm thinking I might need to use a loop since i have many columns but then again there might be a simple solution without having to use a loop. What would be the best way to resolve this issue?

asked Apr 18, 2013 at 18:37
2
  • Are we talking about 4-5 columns? Or about 100 columns? Commented Apr 18, 2013 at 18:39
  • more like 30 to 40 columns Commented Apr 18, 2013 at 18:41

1 Answer 1

8
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'';
SELECT @sql = @sql + '
 ' + QUOTENAME(name) + ' = CASE
 WHEN ' + QUOTENAME(name) + ' = ''NULL'' THEN NULL ELSE '
 + QUOTENAME(name) + ' END,'
FROM sys.columns
WHERE [object_id] = OBJECT_ID('dbo.YourTableName')
AND system_type_id IN (35,99,167,175,231,239);
SELECT @sql = N'UPDATE dbo.YourTableName SET ' + LEFT(@sql, LEN(@sql)-1) + ';';
PRINT @sql;
--EXEC sp_executesql @sql;
answered Apr 18, 2013 at 18:47
6
  • @Aaron, where could we find the lookup table for the system_type_id? Thanks in advance. Commented Apr 18, 2013 at 20:21
  • They're in sys.types Commented Apr 18, 2013 at 20:22
  • @Aaron, maybe I am not in the right page. This is the MSDN page (msdn.microsoft.com/en-us/library/ms188021.aspx) I was looking at, but it doesn't have the list of system_type_id and its corresponding data type. Commented Apr 18, 2013 at 20:24
  • @Travis the documentation does not list all of the values, it just describes the view itself. If you want to see the values, just run a select: SELECT * FROM sys.types; Commented Apr 18, 2013 at 20:25
  • @Aaron. Never mind. It is in the sys.types table.. Commented Apr 18, 2013 at 20:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.