SQL Server创建约束的代码运用


  本文标签:SQL Server创建约束

  以下的文章那个主要是向大家讲述的是 SQL Server创建约束的实际应用代码  。在SQL Server数据库中,创建约束的方式主要有两种,一种是在创建数据库表使同时创建约束,另外一种就是数据库表创建号之后再创建约束  。

  约束的类型一共有五种,分别为:主键约束(primary key),外键约束(foreign key),检查约束(check),默认约束(default)和唯一约束(unique)  。

  

  1. Sql代码   
  2. --创建借阅表   
  3. create table Borrows   
  4. (   
  5. BSID int identity(1,1),   
  6. BID int not null foreign key references Books(BID),   
  7. RID int not null foreign key references Readers(RID),   
  8. BorrowDate datetime default(getdate()),   
  9. ReturnDate datetime,   
  10. primary key(BSID)   
  11. )   
  12. --创建借阅表  
  13. create table Borrows  
  14. (  
  15. BSID int identity(1,1),  
  16. BID int not null foreign key references Books(BID),  
  17. RID int not null foreign key references Readers(RID),  
  18. BorrowDate datetime default(getdate()),  
  19. ReturnDate datetime,  
  20. primary key(BSID)  
  21. )  
  22. Sql代码   
  23. --添加约束   
  24. alter table Readers   
  25. add constraint CK_RaderAge   
  26. check(rage between 15 and 60)   
  27. --追加主键   
  28. alter table Readers   
  29. add constraint PK_Reader   
  30. primary key (RID)   
  31. --追加外键   
  32. alter table Borrows   
  33. add constraint FK_Book   
  34. foreign key (BID) references Books(BID)   
  35. --添加约束  
  36. alter table Readers  
  37. add constraint CK_RaderAge  
  38. check(rage between 15 and 60)  
  39. --追加主键  
  40. alter table Readers  
  41. add constraint PK_Reader  
  42. primary key (RID)  
  43. --追加外键  
  44. alter table Borrows  
  45. add constraint FK_Book  
  46. foreign key (BID) references Books(BID)  
  47. Sql代码   
  48. --追加默认   
  49. alert table Readers   
  50. add constraint DF_ReturnDate   
  51. default (getdate()) for ReturnDate   
  52. --追加默认  
  53. alert table Readers  
  54. add constraint DF_ReturnDate  
  55. default (getdate()) for ReturnDate  

  我把追加默认约束单独那出来,可以发现它是和其它约束的写法不一样的,以上的相关内容就是对SQL Server创建约束的介绍,望你能有所收获  。