表:
學生(*學號,姓名,性別,年齡,專業) create table student( sno char(13) primary key, sname varchar(20) not null, ssex char(2), sage smallint, sdept varchar(30) ); 課程(*課程號,課程名,學分) create table course( cno char(4), cname varchar(40) not null, ccredit smallint not null, 我們可以將欄位的定義和主外鍵的定義分開 primary key (cno) ); 選課(學號,課程號,分數) create table sc( sno char(13), cno char(4), grade smallint, primary key (sno,cno),--定義聯合主鍵 foreign key (sno) references student(sno), constraint FK_sc_cno foreign key (cno) references course(cno) ); 創建一個用戶表 create table tb_user( userid int identity(1,1),【設定整型欄位自動增長】 username varchar(20) not null, userpass varchar(16) not null, groupid int ); 創建用戶組表 create table tb_group( groupid int primary key identity(1001,1), groupname varchar(30) not null );
insert(增加)
使用 insert 陳述句向表中插入資料, insert into table [(column [, column...])] values (value [, value...]); 插入的資料應與欄位的資料型別相同, 舉例: 方法一:不指定列,插入所有欄位 insert into student values('2010040','kangji','男',22,'計算機科學學院');--SQLServer總是嘗試轉化為相同的型別 insert into student values(20100402,'張三','男',22,'計算機科學學院'); 方法二:指定列,插入部分欄位 insert into student (sno,sname) values('20100403','李四'); 注意: 1) 資料的大小應在列的規定范圍內,例如:不能將一個長度為80的字串加入到長度為40的列中, 2) 在values中列出的資料位置必須與被加入的列的排列位置相對應, 3) 字符和日期型資料應包含在單引號中, 4) 插入空值,不指定或insert into table value(null) 注意:在SQLServer 中,''=null; ' '=null; ' '=null; 批量插入資料 insert into u(username,userpass) select sname,sno from student where ssex='男';
update(修改)
使用 update陳述句修改表中資料, update 表名 set 列名=運算式[,列名=運算式 ...] [where where_definition] update語法可以用新值更新原有表行中的各列, set子句指示要修改哪些列和要給予哪些值, update student set sname='康吉' where sno='20100401'; update student set sname='康吉',sage=23 where sno='20100401'; where子句指定應更新哪些行,如沒有where子句,則更新所有的行, 修改還有 null 值的資料 is null select * from student where ssex is null;
delete(洗掉)
使用 delete陳述句洗掉表中資料,
delete from 表名 [where where_definition]
如果不使用where子句,將洗掉表中所有資料,
delete陳述句不能洗掉某一列的值(可使用update對值置null)
使用delete陳述句僅洗掉記錄,不洗掉表本身,如要洗掉表,使用【drop table表名】陳述句,
同insert和update一樣,從一個表中洗掉記錄將引起其它表的參照完整性問題,在修改資料庫資料時,頭腦中應該始終不要忘記這個潛在的問題,
洗掉表中全部資料
delete table 表名;
洗掉表中指定資料
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/21749.html
標籤:SQL Server
上一篇:SQL Server2017 安裝完成后找不到啟動項解決方案
下一篇:sql server查詢(SELECT ,where,distinct,like 查詢,in,is null,group by 和having,order by,as)
