建立表和定義資料完整性

2021-07-05 22:08:08 字數 1943 閱讀 7962

create database tsql2012;

use tsql2012;

--查詢所有資料庫名   sysdatabases主資料庫伺服器中的資料庫

select name from sysdatabases order by name;

--查詢資料庫當前資料庫下所有表名    sysobjects系統表,在資料庫內建立的每個物件(約束、預設值、日誌、規則、儲存過程等)在表中佔一行

select name from sysobjects where xtype='u' order by name;

--建立表employees

create table employees

(empid int not null,

firstname varchar(30) not null,

lastname varchar(30) not null,

hireday date not null,

mgrid int null,

ssn varchar(20) not null,

salary money not null

);--主鍵約束 不允許有null

alter table employees

add constraint pk_employees --建立名字為pk_employees的約束

primary key(empid);

--刪除主鍵約束

declare @csname   varchar(100)   

set @csname='' 

select @csname=name

from sysobjects

where xtype='pk' and parent_obj=object_id('employees') --獲取主鍵約束名字

exec('alter   table   employees  drop   constraint ' + @csname); --刪除約束

--唯一約束 sqlserver只允許有乙個null標記

alter table employees

add constraint  unq_employees_ssn

unique(ssn);

--建立orders表

create table orders

(orderid int not null,

empid int not null,

custid varchar(10) not null,

orderts datetime2 not null,

qty int not null,

constraint pk_orders primary key(orderid)

);--外來鍵約束 不同表

alter table orders

add constraint fk_orders_employees

foreign key(empid)

references employees(empid);

--外來鍵約束 同乙個表

alter table employees

add constraint fk_employees_employees

foreign key(mgrid)

references employees(empid);

--chect 約束 要插入的或修改的行必須滿足此條件

alter table employees

add constraint chk_employees_salary

check(salary >0);

--預設約束 如果插入式沒顯示指定值則使用預設值

alter table orders

add constraint dft_orders_orderts

default(sysdatetime()) for orderts;

實驗2 建立表和定義完整性約束

實驗名稱 建立模式 表和定義完整性約束。實驗內容 在實驗1建立的資料庫的基礎上,參照圖3 4和表3 10建立表和定義完整性約束。實驗目的 熟練掌握表的建立和資料完整性速描定義方法,實踐dbms提供的資料完整性功能,加深對資料完整性的理解。實驗方法 在實驗一建立資料庫的基礎上用create table...

MySQL資料完整性(實體完整性 域完整性)

資料完整性 為保證插入到資料庫中的資料是正確的,防止使用者輸入錯誤的資料 分為實體完整性 域完整性 參照完整性 下節再說 1 實體完整性 實體指的是表中的一行,一行記錄對應乙個實體 通過主鍵實現 主鍵 關鍵字 primary key 特點 不能為null,並且唯一。邏輯主鍵 推薦 例如id,不代表實...

資料完整性

資料完整性定義 是指資料庫中的資料的正確性和完整性。資料完整性的型別 要求的資料。not null。有效檢查。資料的有效範圍檢查。字段檢查約束。資料域。實體完整性。主鍵欄位唯 一 非空。引用完整性引發的問題 1 插入 更新子表記錄的外鍵值在主表主鍵中不存在。2 刪除 更新父表的主鍵記錄有關聯外來鍵記...