Some folks using our software have gone ahead and done a database server move not following our normal steps which accommodate the legacy portions of our software rending nulls = 0 in all databases. So, since they ignored using our protocols, we’re left with a lot of junk null data and a lot of queries for fieldname = 0 that fail because fieldname is null is true instead.
So, how would one go about constructing a stored procedure to revert all nulls (there really should be no nulls) to the default value in a SQL Server database?
I have almost no experience doing stored procedures and absolutely no experience outside of Oracle DBs in stored procedures so please explain what the code is doing if you can answer this with a code sample and if it’s impossible to run procedures over multiple tables, that’s good to know too, in that case I’ll just write a utility to do it (although I can already see that utility taking 9 years to run)
This will list all of the nullable columns in your tables:
You could potentially use a cursor to loop through each, executing some dynamic SQL to update the column definitions. But that could get quite nasty if you have different data types in each of the columns – are they all the same?
Alternatively, you could update all of your SP queries to use:
to eliminate the NULL problem from that side – this will match on NULL -or- Zero.
EDIT:
Ok, assuming you want to update all INT, TINYINT, BIGINT and BIT columns, this script should do it. Use at your own risk though! Backup the DB and restore it as a copy and test it on there. Then, uncomment the table filter in the WHERE clause to test on a single table first. The EXECs are commented, only uncomment once you’ve tested it to screen.
This script will do the following:
Note that 3 will fail if you already have a default constraint on the column. Remove it if you do not need the default value (i.e. you are explicitly inserting a value for every INSERT).
Note: I’ve used cursors for clarity. Feel free to look at @JamesCurtis link if you really don’t want to use them.