SQL基础
use master
go // 先从可用数据库里选一个不同名的数据库名,防止出现”数据库 'Test' 已存在。请选择其他数据库名称“。的提示
if exists(select * from sys.databases where name='Test') //判断数据库是否已经存在
drop database Test //已经存在的话进行删除数据库
go
create database Test
go
use Test
create table Info(
id int primary key identity(1000,1), //primary key主键 identity(1000,1):从第1000开始依次加1
name varchar(10) not null,
tell varchar(11) unique not null, //unique:约束唯一标识数据库表中的每条记录,不能重复
sex nchar(2) check(sex=N'男' or sex=N'女')default(N'男')not null //default(N'男'):默认为男性 check:用于限制列中的值的范围
)
create table Score(
id int primary key identity(1,1),
sid int references Info(id) not null,
subject varchar(50) not null,
score int check(score>=0 and score<=100)not null
)
insert into Info values(N'张三','12345678910',N'男')
insert into Info values(N'李四','12345678911',default)
insert into Info values(N'小张','12345678912',default)
insert into Score values(1000,'语文','50')
insert into Score values(1001,'数学','80')
select* from Info
select* from Score
2、char、varchar和nvarchar的区别
char
char是定长的,也就是当你输入的字符小于你指定的数目时,char(8),你输入的字符小于8时,它会再后面补空值。当你输入的字符大于指定的数时,它会截取超出的字符。
nvarchar(n)
包含 n 个字符的可变长度 Unicode 字符数据。n 的值必须介于 1 与 4,000 之间。字节的存储大小是所输入字符个数的两倍。所输入的数据字符长度可以为零。
varchar(n)
长度为 n 个字节的可变长度且非 Unicode 的字符数据。n 必须是一个介于 1 和 8,000 之间的数值。存储大小为输入数据的字节的实际长度,而不是 n 个字节。所输入的数据字符长度可以为零。

浙公网安备 33010602011771号