Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to constraint no empty strings on an NVARCHAR column

Tags:

sql

sql-server

I add a NOT NULL constraint on my NVARCHAR column so it couldn't allow any empty values. but unfortunately SQL Server deals with NULL and empty values as two separate values!

So how do I make the server throw an exception when inserting nothing to the column?

I'm thinking using the constraint CHECK but I didn't find any samples when used with NVARCHAR columns!

like image 813
Mazen Elkashef Avatar asked Mar 30 '11 17:03

Mazen Elkashef


People also ask

Does NVARCHAR allow NULL?

Allowing NULL values on a column is normally done to allow the absense of a value to be represented. When using NVARCHAR there is aldready a possibility to have an empty string, without setting the column to NULL .

Which constraint can be used to make sure that the column is not left empty?

The NOT NULL constraint guarantees that the column will have a value for each record. In other words, the column will not allow empty values to be stored in it.

Which constraint does not allow to enter blank value only?

The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

Can NVARCHAR hold numbers?

NVARCHAR is a locale-sensitive character data type that allows storing character data in variable-length fields as strings of single-byte or multibyte letters, numbers, and other characters supported by the code set of the necessary database locale.


1 Answers

You could add a check constraint that ensures that the string isn't empty.

CREATE TABLE [dbo].[Foo](     [bar] [nvarchar](50) NOT NULL )  ALTER TABLE [dbo].[Foo] WITH CHECK  ADD  CONSTRAINT [CK_Foo] CHECK  (([bar]<>N'')) 
like image 191
tvanfosson Avatar answered Sep 22 '22 10:09

tvanfosson