sql server 創建table表 及添加各種約束 查看約束 刪除約束 新增表的字段 規則及規則使用方法及應用到表中 時間函數的類型

use Test1
go
create table tb_person
(
id int identity(1,1) primary key not null, --要把該列設置爲主鍵列就用 primary key --
name varchar(20) not null,
sex char(2) not null,
cardid char(25) not null, -- 身份證編號--
age int not null,
currenttime datetime not null,
ksid int not null,
jg varchar(20),
sf varchar(10) null,
city varchar(20) null default '成都', --在添加列的時候可以給添加默認值
address varchar(100) null,
docid int null,
)--使用語法創建表--




--添加主鍵約束--


alter table tb_person
add constraint PK_pid primary key (id) --主鍵約束用PK_....
go


--檢查約束 一定是返回爲true或false的表達結果--
alter table tb_person
add constraint CK_age check (age < 150 and age >0) --比如查詢年齡不能大於150歲 ,小於0歲 關鍵字and--  --檢查約束用CK_....


alter table tb_person with nocheck
add constraint CK_SEX Check(sex = '男' or sex ='女')--檢查性別只能兩種 男,或者 女, 關鍵字 or
go


--唯一性約束,表示該列的值是唯一的--
alter table tb_person
add constraint UQ_CardId unique(cardid)   --唯一性約束用UQ_....
go


--添加的是默認約束--


alter table tb_person
add constraint DK_Address default('地址不詳') for address  --默認約束用DK_....
go


--添加外鍵約束,保證在我們在引用別的表的數據的時候,該數據在其他表示存在的--


alter table tb_person
add constraint FK_KSID foreign key (ksid) references tb_ks(ksid)  --外鍵約束用FK_....
go


 --如果我們在添加約束之前,都已經存在了數據,而這個數據不符合我們的外鍵約束
 --解決方法:
 --1)刪除之前的數據(不推薦)
 --2)在創建約束的時候,告訴系統不再檢查之間的數據。 with nocheck
 -- 語法如下:
alter table tb_person with nocheck
add constraint FK_KSID foreign key (ksid) references tb_ks(ksid)  --外鍵約束用FK_....
go

alter table tb_person with nocheck
add constraint FK_DOCID foreign key(docid) references tb_doc(docid)
go 


--在數據庫中查看約束--
--name表示約束的名稱--
select *from sysobjects where name='ck_age'


--在數據庫中刪除約束,比如刪除上面的年齡--
alter table tb_person
drop constraint ck_age
go


--新增表的字段--
--對錶重新添加一列--
alter table tb_doc
add docage int not null default 30
go


--建議在創建表之後就立馬把外鍵約束創建好










規則:
--規則是一個向後兼容的功能,用於執行一些 CHECK 約束相同的功能。
--CHECK約束是用來限制列值的首選標準方法。
--CHECK約束比規則更簡明,一個列只能應用一個規則,但是卻可以應用多個 CHECK 約束。
--CHECK約束作爲 CREATE TABLE 語句的一部分進行制定,而規則以單獨的對象創建,然後綁定到列上。
--     區別:約束只能正對單表。而規則可以正對多張表。





--規則的使用方法
--1)   對年齡做一個規則的語法--      
--注意在TSQL中變量錢要加@符號
--create rule  規則名字 規則變量 變量的值的範圍
--例如:
create rule agerule as @ageid between 1 and 150   
go


--2)把這個規則應用某個表中
--需要調用系統內置的存儲過程
-- sp_bindrule 第一個參數表示規則的名字,第二個參數制定所限制的列名(表名.列名)
--例如:
exec sp_bindrule 'agerule','tb_person.age'
go




--另外:在sql server 取數據庫服務器的系統時間。取系統時間的函數:getdate()  時間的類型 datetime

發佈了25 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章