Constraint: PRIMARY KEY : Column Constraints « Constraints « SQL Server / T-SQL






Constraint: PRIMARY KEY


1>
2> CREATE TABLE T (
3>     int1 int PRIMARY KEY,
4>     bit1 bit NOT NULL DEFAULT 0
5> )
6> GO
1> INSERT T (int1, bit1) VALUES (1, 1)
2> GO

(1 rows affected)
1> INSERT T (int1, bit1) VALUES (2, 0)
2> GO

(1 rows affected)
1> INSERT T (int1) VALUES (3)
2> GO

(1 rows affected)
1> INSERT T (bit1) VALUES (1)
2> GO
Msg 515, Level 16, State 2, Server JAVA2S\SQLEXPRESS, Line 1
Cannot insert the value NULL into column 'int1', table 'master.dbo.T'; column does not allow nulls. INSERT fails.
The statement has been terminated.
1> INSERT T (int1, bit1) VALUES (3,1)
2> GO
Msg 2627, Level 14, State 1, Server JAVA2S\SQLEXPRESS, Line 1
Violation of PRIMARY KEY constraint 'PK__T__07970BFE'. Cannot insert duplicate key in object 'dbo.T'.
The statement has been terminated.
1>
2> select * from t
3> GO
int1        bit1
----------- ----
          1    1
          2    0
          3    0

(3 rows affected)
1>
2> drop table t
3> GO
1>
2>
           
       








Related examples in the same category

1.Data length: greater than 0
2.Add constraints for two columns
3.Constraint check (Options)
4.Two constraints for one single column: Not NULL and default value