How to prevent inserting empty string in SQL Server?

Setting a field not null doesn’t mean this field doesn’t accept blank strings too! so for preventing empty strings, beside not null definition just add a check constrain to check the empty ones.

create table t(n varchar(64) not null ,constraint chkn check (ltrim(n)!=”));
insert t values('Danial (this is okay!)'),
		('   Pedram (this is okay too!)'),
		('        Code Project folks(this is still okay!)!      '),
		('    '/*Not okay!*/),(null /*Not okay!*/ );

simple remove the spaces with ltrim() function, and check the value should not be as a empty string ”.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s