表:
學(xué)生(*學(xué)號,姓名,性別,年齡,專業(yè))create table student( sno char(13) primary key, sname varchar(20) not null, ssex char(2), sage smallint, sdept varchar(30)); 課程(*課程號,課程名,學(xué)分)create table course( cno char(4), cname varchar(40) not null, ccredit smallint not null, 我們可以將字段的定義和主外鍵的定義分開 primary key (cno)); 選課(學(xué)號,課程號,分?jǐn)?shù))create table sc( sno char(13), cno char(4), grade smallint, primary key (sno,cno),--定義聯(lián)合主鍵 foreign key (sno) references student(sno), constraint FK_sc_cno foreign key (cno) references course(cno)); 創(chuàng)建一個用戶表create table tb_user( userid int identity(1,1),【設(shè)置整型字段自動增長】 username varchar(20) not null, userpass varchar(16) not null, groupid int);創(chuàng)建用戶組表create table tb_group( groupid int primary key identity(1001,1), groupname varchar(30) not null);
使用 insert 語句向表中插入數(shù)據(jù)。insert into table [(column [, column...])]values (value [, value...]);插入的數(shù)據(jù)應(yīng)與字段的數(shù)據(jù)類型相同。 舉例:方法一:不指定列,插入所有字段insert into student values('2010040','kangji','男',22,'計(jì)算機(jī)科學(xué)學(xué)院');--SQLServer總是嘗試轉(zhuǎn)化為相同的類型insert into student values(20100402,'張三','男',22,'計(jì)算機(jī)科學(xué)學(xué)院');方法二:指定列,插入部分字段insert into student (sno,sname) values('20100403','李四'); 注意:1) 數(shù)據(jù)的大小應(yīng)在列的規(guī)定范圍內(nèi),例如:不能將一個長度為80的字符串加入到長度為40的列中。2) 在values中列出的數(shù)據(jù)位置必須與被加入的列的排列位置相對應(yīng)。3) 字符和日期型數(shù)據(jù)應(yīng)包含在單引號中。4) 插入空值,不指定或insert into table value(null)注意:在SQLServer 中,''=null; ' '=null; ' '=null; 批量插入數(shù)據(jù)insert into u(username,userpass) select sname,sno from student where ssex='男';
使用 update語句修改表中數(shù)據(jù)。 update 表名 set 列名=表達(dá)式[,列名=表達(dá)式 ...] [where where_definition] update語法可以用新值更新原有表行中的各列。set子句指示要修改哪些列和要給予哪些值。update student set sname='康吉' where sno='20100401'; update student set sname='康吉',sage=23 where sno='20100401'; where子句指定應(yīng)更新哪些行。如沒有where子句,則更新所有的行。 修改還有 null 值的數(shù)據(jù) is nullselect * from student where ssex is null;
delete(刪除)
使用 delete語句刪除表中數(shù)據(jù)。
delete from 表名 [where where_definition]
如果不使用where子句,將刪除表中所有數(shù)據(jù)。
delete語句不能刪除某一列的值(可使用update對值置null)
使用delete語句僅刪除記錄,不刪除表本身。如要刪除表,使用【drop table表名】語句。
同insert和update一樣,從一個表中刪除記錄將引起其它表的參照完整性問題,在修改數(shù)據(jù)庫數(shù)據(jù)時,頭腦中應(yīng)該始終不要忘記這個潛在的問題。
刪除表中全部數(shù)據(jù)
delete table 表名;
刪除表中指定數(shù)據(jù)
delete from student where xh='A001';
create table class( id int primary key, name varchar(10)); create table student( id int primary key, class_id int references class(id) on delete/update cascade); alter table student add constraint FK_classid foreign key (class_id) references class(id) on update cascade on delete cascade