JJunior
JJunior

Reputation: 2849

Null strings getting added to primary key field

I have a primary key column year in my form.

Whenever the user creates a new form he should populate this field from the drop down.

But if the user makes a mistake and does not select anything from the drop down a null string gets appended "". And when post operation is selected the record gets created in the database table.

My question:
When user posts to the database after making his selection: the primary key column ends up accepting the null string ""

Shouldn't this throw an error as the primary key field should never have a null/empty string ?

I checked the table creation script and the column is set to Not Null and no default value is assigned.

I am using SQL Server 2008.

Upvotes: 1

Views: 886

Answers (1)

Martin Smith
Martin Smith

Reputation: 453287

NULL and empty string are not synonymous in SQL Server as they are for Oracle. A PK can have an empty string.

Of course a PK must be unique so there can be only one such empty string unless it is a composite PK and the other columns have different values.

You should validate this before the insert attempt but could add a check constraint as a last line of defence.

Upvotes: 6

Related Questions