Add the NOT NULL constraint to a column

安稳与你 提交于 2020-01-04 04:55:07

问题


I'm using PHPMyAdmin and I try to add the NOT NULL constraint to a column of my table.

PHPMyAdmin accepts my following query :

ALTER TABLE `wall` MODIFY `token_message` varchar(40) NOT NULL;

But I can still insert empty strings (=NULL), I don't understand why.

PS : If you're going to give me some other queries to add this constraint, note I've have tried these 3 which don't work in my PHPMyAdmin (kind of error : #1064 - You have an error in your SQL syntax; check the manual) :

ALTER TABLE `wall` ALTER COLUMN `token_message` SET NOT NULL;
ALTER TABLE `wall` ALTER COLUMN `token_message` varchar(40) NOT NULL;
ALTER TABLE `wall` MODIFY `token_message` CONSTRAINTS token_message_not_null NOT NULL; 

回答1:


You wrote, "I can still insert empty strings (=NULL)," which sounds like a misunderstanding. In SQL, an empty string does not evaluate to NULL, or vice versa. Try inserting an empty string and doing SELECT from wall where token_message is NULL. You should get zero rows back. Then try doing an insert where you specify NULL (unquoted) as the value for your column, and you should get the expected error message.

If those tests work as expected, then everything is fine, and your problem is actually that you want to prevent blank strings from being inserted. Check out this question for suggestions, or just check for blank strings during validation, before the query.




回答2:


MySQL's column alter syntax requires you to completely re-specify the column. You can't just change one attribute of a column, you have to re-define it completely:

ALTER TABLE wall MODIFY token_message varchar(40) NOT NULL default ''

The only 'SET' version allowed is to change the default value.

ref: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html




回答3:


I think this is a matter of scrubbing your inputs. As octern mentioned, an empty string ('') is not a NULL value in sql. The best way to handle this is to only allow updates through a store procedure which strips out empty strings, even space characters:

CREATE PROC InsertIntoMyDb (@MyVarChar VARCHAR(2000)) AS

SET @MyVarChar = NULLIF(RTRIM(LTRIM(@MyVarChar)), '')

INSERT INTO [TBL] (MyVarChar)
VALUES @MyVarChar

This will truncate any number of spaces to an empty string, turn an empty string into a NULL, and then it will not allow the NULL value to be inserted based on the constraint you already have in place.




回答4:


Try to use this query

Alter table table_name 
change column_name column_name datatype(length) definition

ie,

Alter table wall 
change tocken_message tocken_message varchar(40) NOT NULL DEFAULT


来源:https://stackoverflow.com/questions/10218252/add-the-not-null-constraint-to-a-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!