標籤:
----------------------------/////資料庫操作//////---------------------------
--指向當前使用資料庫
use master
go
--建立資料庫
create database student
on primary --primary 參數可以省略
(
--資料庫檔案邏輯名稱
name=‘studentDB_date‘,
--資料庫物理檔案地址 絕對位址
filename=‘d:\studentDB_date.mdf‘,
--資料庫檔案初始大小
size=10MB,
--資料檔案增長速度
filegrowth=1MB
--最後一行不需要分號
)
---多個資料檔案與日記檔案
,
(
---中間部分與上面一樣 注意要加上上面一行的逗號
)
---多個資料檔案與日記檔案
log on
(
--資料庫日記檔案邏輯名稱
name=‘studentDB_log‘,
--資料庫日記檔案地址 絕對位址
filename=‘d:\studentDB_log.ldf‘,
--資料庫日記檔案初始大小
size=3MB,
--資料日記檔案增長速度
filegrowth=1MB
--最後一行不需要分號
)
go
--檢測資料是否存在
if exists(select * from sysdatabases where name=‘student‘)
--刪除資料庫 不可恢複
drop database student
--分離資料庫
exec sp_detach_db @dbname=資料庫名字
--附加資料庫 注意結尾的分號
exec sp_attach_db @dbname=資料庫名字,
@filename1=‘資料庫主檔案地址‘,
@filename2=‘資料庫日記檔案地址‘
----------------------------/////表操作//////---------------------------
--建表文法
create table 表名
(
欄位1 資料類型 列特性
欄位2 資料類型 列特性
..........
)
列特性:
1. NULL 或 NOT NULL
2.是否是識別欄位 identity
3.是否有預設值 default
3是否為主鍵 primary key
--------------------------------
use master
go
--檢測表是否存在
if exists(select * from sysobjects where name=‘student‘)
--刪除表 不可恢複
drop table student
--建立表
create table student
(
studentid int identity(10000,1) primary key, --學號自動成長 主鍵 從10000開始
studentname varchar(10) not null,
sex varchar(4) null,
address varchar(100) default(‘地址不詳‘) -- 定義預設地址
)
go
--插入記錄文法
insert [into] 表名 [列名] values(值集合)
--更新記錄文法--不帶查詢條件更新所有資料
update 表名 set 列名=更新值 [where 查詢條件]
--刪除記錄文法--不帶查詢條件刪除所有資料
delete from 表名 [where 查詢條件]
truncate table 表名 --這種方式刪除後的表格可以恢複填充自增的數控
----------------------------/////查詢語句//////---------------------------
--基本查詢文法
select [欄位] from [表名] where [查詢條件]
----------------------------/////約束條件//////---------------------------
--添加約束的基本文法
alter table 表名
add constraint 約束名 約束類型_限制欄位
--約束名的取名規則:約束類型_限制欄位
-- pk_欄位 主鍵(primary key)約束
-- uq_欄位 唯一(unique key)約束
-- ck_欄位 檢查(check key)約束
-- df_欄位 預設(default key)約束
-- fk_欄位 外鍵約(foreign key)束
--樣本
alter table student
add constraint pk_studentid primary key(studentid) --主鍵約束
alter table student
add constraint uq_studentid unique(studentid) --唯一性限制式
alter table student
add constraint ck_sex check (sex=‘男‘ or sex=‘女‘) --檢查約束
alter table student
add constraint df_address default(‘地址不詳‘) for address --預設約束
alter table student
add constraint fk_class foreign key(class) references clsaabom --主外鍵約束
SQL 基本操作