SQL 基本操作

來源:互聯網
上載者:User

標籤:

----------------------------/////資料庫操作//////---------------------------
--指向當前使用資料庫
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 基本操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.