2021-06-13

SQL Server学习 01

1、创建数据库
	create database DBTEST 
	on 			--数据文件
	(								
		name='DBTEST',  			--数据库名
		filename='URL地址',  		--数据库的物理地址
		size=5MB, 				    --初始大小
		filegrowth=2MB     		 	--文件增长方式 
	)
	log on		--日志文件
    (
		name='DBTEST_log',  			--数据库名
		filename='URL地址',  		--数据库的物理地址
		size=5MB, 				    --初始大小
		filegrowth=2MB     		 	--文件增长方式 
	)
	
实例:
if exists(select *from sys.databases where name='DBTEST')
drop database DBTEST

create database DBTEST 
on
(
	name='DBTEST',
	filename='D:\Desktop\我的数据库\MyDB\DBTEST.mdf',
	size=5MB,
	filegrowth=2MB
)

log on
(
	name='DBTEST_log',
	filename='D:\Desktop\我的数据库\MyDB\DBTEST_log.mdf',
	size=5MB,
	filegrowth=2MB
)
  1. 数据库中创建表
    语法:建表之前需要先use DBname来选择具体需要哪个数据库。

     create table 表名 
     (
     	字段名1 数据类型,
     	字段名2 数据类型,
     		...
     )
    
实例:
		use DBTEST    --使用数据库DBTEST
		if exists(select *from sys.objects where name='TableTest' and type='U')
		drop table TableTest
		--建表
		create table TableTest
		(
			id int primary key identity(1,1), --主键,初始值1,步长为1
			name varchar(20) not null,
			score int,
			detail text
		)

几个数据类型的特点
1、char() :定长,如果是char(10),哪怕只有2个字节,也占领10个字节。
2、varchar():变长,如果varchar(10)是最多存储10个字节。
3、text: 长文本,但是检索时会效率比char\varchar低。
4、date:年月日
5、datetime:年月日时分秒
6、smalldatetime:范围比datetime更小的时间。
7、decimal(整数位,小数位):比如decimal(7,3)表示个位数为7,小数位为3。

注意:char、varchar、text前面添加一个n字母,代表是unicode字符编码类型。
还有一点:如果我们定义的变量是个sql中早有的关键字,则需要用[]来括起来就可以使用。

常见的约束:
1、primary key identity(1,1):代表主键,且从1开始步长为1。
2、references 表名(字段名):外键,用于引入其他表格中的主键字段。
3、default(值):用于给字段设置默认值。
4、check():限制字段的值。
5、getdate():此函数用于获取当前系统时间的。

综合案例
use DBTEST

create table DepartmentInfo(
	DepartmentID int primary key identity(1,1),
	DpartmetName nvarchar(20),
)

create table Person (
	PersonID int primary key identity(1,1),
	DepartmentID int references DepartmentInfo(DepartmentID) not null,
	PersonName nvarchar(20) not null,
	PersonSex nvarchar(1) default('男') check(PersonSex='男' or PersonSex='女'),
	PersonBirth smalldatetime not null,
	PersonSalary decimal(10,2) check(PersonSalary>=5000 and PersonSalary<=1000000)not null,
	PersonPhone varchar(20),
	PersonAddress varchar(3000),
	PersonAddTime smalldatetime default(getdate())
)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值