Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

sql server - SQL replace all NULLs

I have a big table with some NULLs in it. What is the easiest possible way to select from the table with 0's instead of NULLs.

Or if there is no easy way to do that, I'm willing to physically replace all the nulls with 0's in the table.

There is lots of columns, I don't want to have to go through each one with something like ISNULL(FieldName,0) AS FieldName.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As many here have said, the best approach is ISNULL(), however if you want an easy way to generate all those ISNULL()'s use the following code:

SELECT 'ISNULL([' + COLUMN_NAME + '], ' + 
  CASE 
    WHEN DATA_TYPE = 'bit' THEN '0'
    WHEN DATA_TYPE = 'int' THEN '0'
    WHEN DATA_TYPE = 'decimal' THEN '0'
    WHEN DATA_TYPE = 'date' THEN '''1/1/1900'''
    WHEN DATA_TYPE = 'datetime' THEN '''1/1/1900'''
    WHEN DATA_TYPE = 'uniqueidentifier' THEN '00000000-0000-0000-0000-000000000000'
    ELSE '''''' -- everything else get's an empty string
  END + ') AS [' + COLUMN_NAME + '],'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TableName'

This will make the tedious job a whole lot easier, you then just have to edit the output to account for the various field types (int, varchar, dates, etc)

Edit: accounting for various datatypes with default values..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...