I'd like to update all NULL fields in one table to 0. Of course
UPDATE mytable SET firstcol=0 WHERE firstcol IS NULL
would do the job. But I wonder if there´s a smarter solution than just c&p this line for every column.
I'd like to update all NULL fields in one table to 0. Of course
UPDATE mytable SET firstcol=0 WHERE firstcol IS NULL
would do the job. But I wonder if there´s a smarter solution than just c&p this line for every column.
You could do this - repeat as necessary for each column:
Example:
UPDATE
If you want to alter the table structure by changing columns so that they no longer accept nulls, you could do it with a stored procedure. The following stored procedure queries the INFORMATION_SCHEMA COLUMNS for information about columns in a given database table. From that information, it builds up a prepared statement which is then used to alter the table structure. You may need to tweak it to suit your exact requirements - at the moment, it looks for
INT
columns which do not haveNOT NULL
set:Example:
The following line displays the command that is to be executed, and may be removed from the stored procedure if necessary:
Not without an intermediate technology or cursor. You could use
DESCRIBE mytable;
to get the column names and loop over them to build yourUPDATE
queries.So it is possible. But by the time it took you to write that, you probably just could have copy and pasted ;)
This worked for me!
This is mike's answer but without the quotes for columns on the left !
Note: If you are trying to set your values '0' instead of an empty string if a column's datatype is int
Can you just
ALTER
the columns toNOT NULL DEFAULT 0
?You can do this in a single statement, as per MySQL documentation:
I don't believe there is; any statement that worked on rows that didn't satisfy the where clause would update rows you didn't intent to update. Jason's answer is correct, but, I think, a bit unsafe, unless you are really sure that's what you want.
You may want to alter your columns to
NOT NULL
.Test case:
Result: