下载数据库
我下载的是 SQL Server 2022 Developer 及 SQL Server Management Studio 20.0.70.0
下载方法参照文章
表的使用
创建表和删除表
创建表并插入数据
Use Master;--系统数据库
GO
CREATE DATABASE scdatabase;--创建数据库,如果该数据库已经存在则错误
GO
Use scdatabase;
GO
CREATE TABLE student ( --创建表 student
sno INT PRIMARY KEY, --属性名 数据类型 (是主码加PRIMARY KEY)
sname VARCHAR(50),
sex CHAR(1)
);
CREATE TABLE teacher (
tno INT PRIMARY KEY,
tname VARCHAR(50),
salary DECIMAL(10, 2)
);
CREATE TABLE course (
cno INT PRIMARY KEY,
cname VARCHAR(100),
credit INT,
pre_cno INT,
FOREIGN KEY (pre_cno) REFERENCES course (cno)--设置外码
);
CREATE TABLE sc (
sno INT,
cno INT,
score INT,
PRIMARY KEY (sno, cno),
FOREIGN KEY (sno) REFERENCES student (sno),
FOREIGN KEY (cno) REFERENCES course (cno)
);
CREATE TABLE tc (
tno INT,
cno INT,
PRIMARY KEY (tno, cno),--多个属性组成主码
FOREIGN KEY (tno) REFERENCES teacher (tno),
FOREIGN KEY (cno) REFERENCES course (cno)
);
--在表中插入数据
INSERT INTO student VALUES (20223041, 'Mike', 'M');
INSERT INTO student VALUES (20223042, 'Lucy', 'F');
INSERT INTO teacher VALUES (20072616, 'Rong', 50000.00);
INSERT INTO teacher VALUES (20082189, 'Lee', 60000.00);
INSERT INTO course VALUES (101, 'Database System', 3, NULL);
INSERT INTO course VALUES (102, 'Software Engineering Introduction', 4, 101);
INSERT INTO course VALUES (103, 'Data Structure', 4, 101);
INSERT INTO sc VALUES (20223041, 101, 90);
INSERT INTO sc VALUES (20223041, 102, 96);
INSERT INTO tc VALUES (20072616, 101);
INSERT INTO tc VALUES (20072616, 104);
删除表
DROP DATABASE scdatabase;