How to restrict Blank values in Primary Key column

I have a database of sql server 2008 which I am using to display in a gridview. I have written some code to add new rows in asp.net and C# as Code behind.

When ever a row is added through the Programming I have put some checking which will not allow the required values to be Null.

But, here comes my problem when ever any one of the user adds a new row manually by opening the Database, then a blank value is allowing in the Primary key column which is not 'Null value'.

So, here I have to restrict even not to allow blank values in primary key column, how can I solve this problem.


你需要检查约束

ALTER TABLE [TableName]
    ADD CONSTRAINT [CK_PrimaryKeyNotEmpty]
        CHECK
        (
            LEN([ColumnName]) > 0
        )

I'm having trouble figuring out what you actual question is.

1) If you need to make a column not accept null values:

Add a constraint to the column in the db:

ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL

See: Altering a column: null to not null


2) If you need to restrict your PK column to only certain values add a constraint:

ALTER TABLE Table ADD CONSTRAINT CK_Table_Column_Range CHECK ( Column >= 0 )

链接地址: http://www.djcxy.com/p/76284.html

上一篇: 在SQL Server中没有主键的现有表上创建主键

下一篇: 如何限制主键列中的空白值