建立資料庫
,這一篇當然就是建立資料庫中的表。
建立資料表的常規語法為:
[sql]
create table 表名稱
(列名稱1 資料型別,是否為空,約束,
列名稱2 資料型別,是否為空,約束,
列名稱3 資料型別,是否為空,約束,
....
)[/sql]
其中資料型別可以參看msdn中的說明,很詳細,傳送門。
下面就在上次建立的studb中建立乙個student表:
[sql]
use studb --轉到studb資料庫
goif exists(select * from sysobjects where name='student') --如果有同名的,刪除
drop table test1
gocreate table student
(tid int identity(1,1) not null, --tid,以種子1,增量1自增長,不可為空
tname varchar(20) not null, --姓名,20varchar型別長度,不可為空
tage int not null default 18 check(tage > 0), --年齡,int型,不可為空,預設18,大於0約束
tintertime datetime not null default getdate() --加入時間,datetime型別,不為空,預設為插入時系統世界
)alter table student add constraint rk_uid --建立主鍵,tid
primary key(tid)
insert into student (tname,tage) values('ceshi1',25) --插入一條資料,沒有插入的字段,按預設處理
[/sql]
最終形成的表:
建立了簡單的資料表後,還可以對錶進行增刪或者進行約束和索引。
我們希望在student表中增加兩個字段,班級id和民族。
[sql]
alter table student add cid int null
alter table student add nation varchar(10) null
[/sql]
注:在已有的資料表中增加欄位時需要注意的是不能指定當前欄位不為空。
現在student表示下面的樣子:
但我現在沒有班級表,不想要cid,可以刪除之:
[sql]alter table student drop column cid[/sql]
如果現在我想把原先的年齡的預設值從18改為16,改怎麼做?預設值是不可以直接更改的,所以我們只能刪了原來的預設值,然後再重新新增,但又有個問題,如何得到預設值的名字呢?這裡需要一些變數的知識了,但暫且先不說,只要可以滿足當前的功能即可。
[sql]
declare @dname varchar(100) --宣告變數
select @dname=name from sysobjects where xtype = 'd' and parent_obj = object_id('student') and name like '%tage%' --查詢預設值的名稱
--alter table student drop constraint @dname --刪除語句不支援變數,所以要用下面的拼接函式
exec('alter table student drop constraint ' + @dname)
alter table student add constraint tagedefault default '16' for tage
[/sql]
乙個簡要的總結:
刪除資料庫/表/索引
drop database 資料庫名
drop table 表名
drop index 表名.索引名
drop procedure 儲存方法名
drop view 檢視名
.建立約束
alter table 表名 add constraint 約束名 約束型別
主鍵約束:primary key(列名)
外來鍵約束:foregin key(列名) references 主表名(主鍵名)
唯一約束:unique(列名)
預設約束:default(預設值) for 列名
check約束:check(條件)
//標識列可以在建立列的時候,使用identity(1,1)
簡要總結的**在這裡。
T SQL入門攻略之12 建立資料表
title t sql 入門攻略之12 建立資料表 author wufeng4552 date 2010 06 18 使用主鍵約束 主鍵不允許重複也不允許有空值 1單字段主鍵 if object id testtable u is notnull drop table testtable crea...
T SQL入門攻略之12 建立資料表
使用主鍵約束 主鍵不允許重複也不允許有空值 1單字段主鍵 if object id testtable u is notnull drop table testtable create table testtable col1 varchar 10 col2 int,col3 datetime,co...
T SQL入門攻略之12 建立資料表
title t sql 入門攻略之12 建立資料表 author wufeng4552 date 2010 06 18 使用主鍵約束 主鍵不允許重複也不允許有空值 1單字段主鍵 if object id testtable u is notnull drop table testtable crea...