SQL Server資料庫操作(二)

2022-01-24 03:58:17 字數 2211 閱讀 8041

一、新增約束的語法

alter table 表名 add constraint 約束名 約束型別 具體的約束說明

use

studentmanagedb

go--

新增約束,建立主鍵約束

ifexists(select

*from sysobjects where name=

'pk_studentid')

alter

table students drop

constraint

pk_studentid

alter

table students add

constraint pk_studentid primary

key(studentid)

--新增約束,建立唯一約束

ifexists(select

*from sysobjects where name=

'uq_studentidno')

alter

table students drop

constraint

uq_studentidno

alter

table students add

constraint uq_studentidno unique(studentidno)

--

新增約束,建立檢查約束

ifexists(select

*from sysobjects where name=

'ck_age')

alter

table students drop

constraint

ck_age

alter

table students add

constraint ck_age check(age between

18and26)

ifexists(select

*from sysobjects where name=

'ck_phonenumber')

alter

table students drop

constraint

ck_phonenumber

alter

table students add

constraint ck_phonenumber check(len(phonenumber)=

11)

--

建立外來鍵約束

ifexists(select

*from sysobjects where name=

'fk_classid')

alter

table students drop

constraint

fk_classid

alter

table students add

constraint fk_classid foreign

key(classid) references studentclass(classid)

實體完整性

a.能夠唯一標識表中的每一條記錄。

b.實現方式:主鍵、唯一鍵、identity屬性。

域完整性

a.表中特定列資料的有效性,確保不會輸入無效的值。

b.實現方式:資料型別限制、預設值、非空值。

引用完整性

a.維護表間資料的有效性、完整性。

b.實現方式:建立外來鍵,關聯另一表的主鍵。

主鍵的選擇

a.最少性原則:盡量選擇單個鍵作為主鍵。

b.穩定性原則:盡量選擇數值更新少的列作為主鍵。

外來鍵使用

a.要求資料型別、資料長度必須與對應的主鍵表字段完全一致。

b.新增資料時,要首先新增主鍵表,在新增外來鍵表。

c.刪除資料時,要首先刪除外來鍵表資料,在刪除主鍵表資料。

完整資料庫建立步驟

建庫---->建表---->主鍵約束---->域完整性約束---->外來鍵約束

插入資料的過程

驗證主鍵、主外來鍵關係、檢查約束……---->插入成功

sqlserver跨資料庫操作

1 方法一 建立鏈結伺服器 建立鏈結伺服器 exec sp addlinkedserver srv lnk sqloledb 遠端伺服器名或ip位址 exec sp addlinkedsrvlogin srv lnk false null,使用者名稱 密碼 go 查詢示例 select from s...

ADO 操作SqlServer資料庫

connectionptr物件 connection物件的execute方法執行sql命令 execute方法的原型如下所示 recordsetptr connection15 execute bstr t commandtext,variant recordsaffected,long optio...

C 操作Sql server資料庫

建立資料庫 public string createmssql string dbname,string dbpath if string.isnullorempty dbname if string.isnullorempty dbpath dataset ds new dataset strin...