开发者

How to get rid of NULL values in SQL Server 2008 table

I have a table like:

1   0.22    0.14    0.05
23  11      0.32    0.16
4   NULL    1       0.39
NULL NULL   .8      1
NULL .5     .7      NULL 

I want to modify the table to become

1   0.22  0.14  0.05
23   1    0.32  0.16
开发者_Python百科4   -1      1   0.39
-1  -1     .8     1
-1  .5     .7    -1

If you look I changed the NULL by -1

I was trying:

SELECT
  coalesce([a1], -1), coalesce([a2], -1),coalesce([a3], -1), coalesce([a4], -1)
FROM tableee;

Which is correct, but when I do a SELECT * I get the table with null values...

How do I modify the table so when I do a SELECT * I do not get NULL but -1 instead?


If you want to change the values in the table you need to update the table:

UPDATE Tableeee t
SET t.a1 = COALESCE(t.a1,-1),
    t.a2 = COALESCE(t.a2,-1),
    t.a3 = COALESCE(t.a3,-1)
    t.a4 = COALESCE(t.a4,-1)

Or you can change the columns to not nullable and give a default value of -1. You will probably want to do this if you have that requirement. Updating the data would just be a bandaide, you need to enforce this requirement in the DB.


You could change the table schema so that the columns are non-nullable, and have a default value of -1. That should alter the data so that all of the NULL values become -1.

If you don't want to actually change the data but only the data set returned by the query, consider creating a view based off of your COALESCE()ing query. Then you can use that view whenever you want to see -1 in place of NULL.


There is no way to actually modify the table so that you get -1 instead of null with a select *. You are allowing nulls for those columns so it is not desirable logic to hide the nulls.

Now that being said, you have three options:

1) Update the table to not allow nulls in those columns and then set the default to -1 (or use a trigger) note: This requires admin priviledges, which you may not have.
2) Always do a select with your coalease or an isnull() test
3) You could make a view of the same table and then in the view select do your coalesce() or isnull() logic, then you could just select * from the view, and it would give you the same table but with the null changed out.

Just FYI, option 2 or 3 has overhead, so only do this if #1 is not an option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜