Select 查、insert 插、update 改 或delete 删
________--数据库创建______________________________
CREATE DATABASE [sample_db] ON PRIMARY --创建数据库名字叫sample_db
(
NAME='sample_db',--数据库里面叫的名字
FILENAME='D:\DZQDB\sample.mdf',
SIZE=5MB, --数据库多大
MAXSIZE=30MB,--最大多少
FILEGROWTH=5%--每次增长1536kb
)
LOG ON --日志文件
(
NAME='sample_log',
FILENAME='D:\DZQDB\sample_log.ldf', --FILENAME保存路径
SIZE=1024KB,--日志多大
MAXSIZE=8192KB,
FILEGROWTH=10%
)
GO
_________________________________________
数据库表创建____________________________________
CREATE TABLE table_emo --数据库表创建 CREATE TABLE 创建表
(
e_id CHAR(18) PRIMARY KEY,
e_name VARCHAR(25) NOT NULL,
e_deptId INT,
e_phone VARCHAR(15) CONSTRAINT up_phone UNIQUE
);
_________________________________________
查看自设内存_________________________________
sp_spaceused --查看自设内存
_________________________________________
查看数据库状态____________________________
USE sample_db --查看数据库状态
GO
SELECT DATABASEPROPERTYEX('test','Statues')
AS 'sample_db数据库状态'
_________________________________________
-修改数据库容量_______________________________
ALTER DATABASE sample_db --修改数据库容量alter database
MODIFY FILE --修改文件 modify file
(
NAME=sample_db, --指定数据库名字
SIZE=30MB
);
GO --开始
_ ________________________________________
_________________________________________
CREATE TABLE autt
(
auth_id int PRIMARY KEY,--数据表主键
aute_name VARCHAR(20) NOT NULL UNIQUE, --作者名称 不能为空 not noll可以为空
auth_gender tinyint NOT NULL DEFAULT(1) --作者性别 男(1) 女(0)
);
_________________________________________
——————————————————————————————————
sp_addtype HomeAddress2,'varchar(128)','not null'--自定义数据类型
sp_droptype HomeAddress2--删除自定义数据类型
drop database sample_db; --删除,在使用的时候不可以被删除
_____________________________________________
CREATE TABLE teacherr
(
id INT NOT NULL PRIMARY KEY,
nane VARCHAR (20) NOT NULL,
birthday DATE,
sex VARCHAR (4),
cellphone VARCHAR(18)
)
--一张id表
_____________________________________________
__
数据表的插入__
insert into t_学生(t_账号,t_密码,姓名) values('{txt_用}','{txt_密码.Text}','{txt_qq.Text}')
--如果有缺少也可以用这个指定类容
_________________________________________
INSERT INTO teacherr VALUES(123,'张三','1978-10-10','男','00001001'), --插入一条记录 增加 添加
(37,'张四','1972-10-10','男','01231001'),
(4,'张五','1938-10-10','男','00003211001')
SELECT * FROM teacherr --查询
___________________________________________
数据的更新
SELECT * FROM teacherr WHERE id=1 --修改前查询
UPDATE teacherr --update 更新 里面的值
SET birthday='1992-12-31',cellphone='0012400' WHERE id=1; --只修改id为1资料 删掉WHERE就修改所有的为设定 SET birthday='1992-12-31';
SELECT * FROM teacherr WHERE id=1; --修改后查询
_____________________________________________
_数据库的删除__________________________________________
SELECT * FROM teacherr --修改前查询
DELETE FROM teacherr WHERE id=1;--删除id为1的这条记录
SELECT * FROM teacherr --修改后查询
删除所有
____________________________________________
_数据表查询__________________________________________
select *from teacher --查询所有
select distinct id from teacherr --distinct 不显示重复
select id, sex from teacher --查询id 和sex
select id, nane, birthday, sex,cellphone-5 from teacherr --输出后面简去5的值
select TOP 2* from teacherr --只输出前2行
select TOP 2* from teacherr WHERE sex='男' ; --查询为男的性别
select TOP 2* from teacherr WHERE not sex='男' ; --查询不男的性
select stu_info *0.2 成绩 from teacherr; --吧成绩打8折
SELECT 姓名 FROM t_学生 where t_账号='10001' --查询学生表中账号为10001的姓名
1.select top 10 * from 成绩信息
作用:查询前十行数据
2.select top 10 percent * from 成绩信息
作用:查询前10%行的数据
select top 20 * from t_xiaoxi order by amount desc --倒序输出后20条语句
select * from teacherr WHERE sex='男' AND age>18 ; --查询为男的性别,岁数大于18岁
select * from teacherr WHERE age>18 or abc>18 ;-- 满足2个其中一个就执行出了
select * from teacherr WHERE BETWEEN 50 AND 90; --查询50到90之间的值
select * from teacherr WHERE name LIKE'马%'; ----查询前面是马开头的名字
select * from teacherr ORDER BY chengji DESC;--吧零年从大到小排序
____________________________________________
全局变量_________________________________________
declare @username varchar(20)
declare @pwd varchar(20)
set @username='newadmin'
select @pwd='newpwd'
select '用户名:'+@username+'密码:'+@pwd --全局变量
_____________________________________________
查询最后一条语句___________________________________________
declare @stuScore int --声明一个变量 @stuScore
select s_score from teacherr
select @stuScore =s_score from teacherr --查询最后一条语句
select @stuScore as lastscore
_____________________________________________
设置职位
___________________________________________
use sample_db
select nane,s_score,
case nane
when '张五' then '班长'
when '张四' then '副班长'
when '张三' then '学习代表'
when '张八' then '课代表'
else '无'
end
as '职位'
from teacherr
_____________________________________________
print 输出语句
___________________________________________
declare @name varchar(10)='小明'
declare @age int=21 --定义岁数为25岁
print '姓名 林玲'--输出语句
print @name+' '+convert(varchar(20),@age) --输出答案 convert类型转换
姓名 林玲
小明 21
___________________________________________
数据库while循环
___________________________________________
declare @count int –定义
select @count=0
while @count <10
begin --开始
print 'count='+convert(varchar(8),@count)
select @count=@count+1
end --结束
print 'loop over count= '+convert(varchar(8),@count)
_____________________________________________
if判断语句___________________________________________
declare @abc int;
select @abc=40
if @abc<30
print '小于30'
else
print '大于30'
_____________________________________________
数据库的sleep延迟语句
___________________________________________
declare @name varchar(30);
set @name='admin';
begin
waitfor delay '00:00:10'; --和sleep语句一样,最多不可超过24小时
print @name
end;
_____________________________________________
字符串函数
___________________________________________
--select ASCII('a'),ASCII('b'),ASCII(1);--数组不需要字符括起来 转话成ascii码
--select char(115),char(43);--和ascii相反
--select left('football',4);--获取前4位的数
--select right('football',4);--获取后4位的数
--select str(123.12,6,1),str(123.12,3,2);--第一个是数第2个表示如果超过n位小数那么输出*,第3个表示获取多少位小数、
--select reverse('123456');--八里面的数反过来输出
--select len('noo');--统计里面有多少个字符
--select charindex('a','balana',)--查找第一次所在的位置
--select lower('qweAqwAdaA') --吧大写转换成小写字母
--select upper('qweAqwAdaA') --吧小写转换成大写字母
--select replace('xxx.baidu.com','x','w')--替换函数吧x替换成w
--select replace('xxx.baidu.com','x','w')--替换函数吧x替换成w
_____________________________________________
数学函数
___________________________________________
--select abs(2),abs(-123123),abs(-111111111111.11112223);--负数转正数函数
--select pi();--圆周路
--select sqrt(9)--平方根函数
--select rand();--随机函数
--select round(1.38,1), round(1.38,0) ,round(11.38,-1) --四舍5入函数
--select sign(-12), sign(0), sign(12) --判断正副正的话为1负的为2
--select floor (-3.35), floor (3.35) --找到不大于3.35的最大整数h
--select power(2,2) --求平方2的2次方
--select log10(3) --求对数前面10是求10为低3为数的答案
___________________________________________
文本和图形函数
___________________________________________
create table t1(c1 int,c2 text)--创立了table类型的t1表里面有2个值为c1,c2
insert t1 values ('1','This is text.')--在里面方一点数局
--insert 插入 values 值
select c1,textptr(c2) from t1 where c1=1;--查询t1表中c1的指针
select c1, 'This is text.'=TEXTVALID('t1,c2',textptr(c2))from t1;--查询值是否在如果在的话就返回1
_______________________________________
年月日 时间函数
___________________________________________
select getdate();--获取当前日期时间函数
select getutcdate();--世界标准天数
select day('2021-07-22');--获取天函数
select month('2021-07-22');--获取月份函数
select year('2021-07-22');--获取年份函数
select weekday('2021-07-22')—获取星期几的函数
_____________________________________________
___________________________________________
select datename(year,'2021-07-22 17:29:15'),-- datename获取时间的字符串返回指定的时间类型的的数 第几年
datename(weekday,'2021-07-22 17:29:15'), --dayofyear这一年的星期几
datename(dayofyear,'2021-07-22 17:29:15')--dayofyear这一年的第几天
-- datename(weekday,1,'2021-07-22 17:29:15'), --这个1表示加一天
_____________________________________________
系统函数
___________________________________________
use sample_db --在sample_db数据库里面找
select col_length('teacherr','id');--查询teacherr表中id最多是多少位
select col_name(object_id('sample_db.dbo.teacherr'),1);--查询数据库中dbo.teacherr表中名称
use sample_db
select datalength(sex) from teacherr where id=3;--看数据的长度是多少
select db_id('master'),db_id('sample_db')--数据库编号名称
select host_id() --查看数据服务的名称id号码
select host_name() --查看数据名称
select host_id() --查看数据服务的名称id号码
select host_name() --查看数据服务的名称是什么 DZQDB123
select object_id('sample_db.dbo.teacherr');--返回teacherr表的id
select SUSER_ID('kevin\administrator');--返回安全标识号
use sample_db;--sample 数据库名称
select user_name();--返回数据库前缀名
_____________________________________________
保存方法
___________________________________________
select *from sample_db.dbo.teacherr;--查询sample数据库下面的teacgerr文件
以表格形式保存
以文本形式保存
_____________________________________________
取名字
___________________________________________
select nane as '名字', stu_info '成绩'-- as 给列取别名
from teacherr;
_____________________________________________
--查询列和 sum
___________________________________________
use sample_db --数据库名称
select sum(stu_info) as 查询 –sum 求列和
from teacher --表名称
where id=4; --需要求的id where 在哪里
use sample_db
select sum(stu_info) as 查询–sum 求列和
from teacherr
group by id; --group by: 分组依据
select avg(stu_info) as 求平均值
from teacherr
where id=3;
select max(stu_info) as 最大值 from teacherr;
select min(nane)as 最小 from teacherr;--安装字符排序从a-z
select max(nane) as 最大 from teacherr;--安装字符排序从a-z
select count(*) as 统计行数 –统计这张表一共有多少行
from teacherr
select count(cellphone) as 统计行数--统计所有cellphone不为空的数
from teacherr
_____________________________________________
7.5 嵌套查询 ___________________________________________
//未看懂
_____________________________________________
多表连接
___________________________________________
select teacherr.id,name,teacherr.nane ,teacherr.sex,age,stu_info,birthday
from teacherr inner join biao --inner join 内连接 吧teacherr表和biao表连接起来
on teacherr.id =biao.id; --on 等于连接
teacherr biao
select teacherr.id,name,teacherr.nane ,teacherr.sex,age,stu_info,birthday
from teacherr inner join biao --inner join 内连接 吧teacherr表和biao表连接起来
on teacherr.id <>biao.id--on 不等于连接
use sample_db
select teacherr.id,biao.name
from teacherr inner join biao
on biao.id=teacherr.id and teacherr.id=1 --带条件的查询
_____________________________________
排序
___________________________________________
use sample_db
select ROW_NUMBER() over(order by age asc) as age,name --ROW_NUMBER()排序函数 根据age的大小进行排序
from biao
use sample_db
select rank() over(order by age asc) as age,score,name --根据age大小进行排序rank函数是排名函数。 rank函数最常用的是求某一个数值在某一区域内的排名。 即返回一个数字在数字列表中的排位。 数字的排位是其大小与列表中其他值的比值,如果列表已排过序,则数字的排位就是它当前的位置。
from biao
use sample_db
select dense_rank() over(order by age asc) as age,name --它为分区或结果集中的每一行分配排名,而排名值没有间隙。 行的等级从行前的不同等级值的数量增加1。
from biao
use sample_db
select ntile(3) over(order by age asc) as age,name --设置有几组
from biao
_____________________________________________
插入数据
___________________________________________
create table person --需要创建的表
(
id int not null primary key,
name varchar(40) not null default '',
age int not null default 0,
info varchar(50) null
);
insert into person (id,name ,age ,info)—需要插入的数据
values (1,'Green',21,'Lawyer');
insert into person (id,name ,age ,info)--需要插入的数据
values (2,'Suse',22,'dancer');
insert into person (id,name ,age ,info)--需要插入的数据
values (3,'Mary',24,'Musician');
insert into shurubiao(id,nane)--insert into 插入到 ___里面(要插入的值)
select id,nane from teacherr;--用这个数据库的id和nane插入到shurubiao里面数据
select *from teacherr;--查询
_____________________________________________
数据插入
___________________________________________
select *from biao where id=4;--查询
update biao set name='张100',age=100 where id=4;--修改id为4中name和age的数据 update 更新相当于修改
select *from biao where id=4;--查询
select *from biao where id=4;--查询
update biao set name='张100'where age between 12 and 15;--吧从age为12到15中的name数据全部改成张100 between...and 在……之间
select *from biao where id=4;--查询
select* from biao
update biao set name='李4';--吧所有biao表里面的name全部改成李4 set:以biao表中的name值为修改目标
select* from biao
_____________________________________________
数据删除
___________________________________________
select* from biao
delete from biao where sex='女';--吧数据表中的所有为女的数据全部删除 delete from 从...删除
delete from biao where sex='女'; --设置前面表名,修改where设置就可以指定数据删除
select* from biao
delete from autt;--删除表中所有数据
select *from autt;
use sample_db
go
drop table autt;--删除autt表
_____________________________________________
规则的基本操作
___________________________________________
--创建规则
use sample_db;--选择数据库
go
create rule g_guizhe --创建规则名称 create rule创建规则
as
@guizhe>0 and @guizhe<100 --设置规则为不可以小于0并且不可以大于100
--绑定规则
use sample_db
go
exec sp_bindrule 'g_guizhe','biao.score' -- 吧自己写的g_guizhe规则绑定到score列中 exec 执行 bindrule 规则名 (规则名字,数据表.列)
如果值超出就会发生错误
--规则解除
exec sp_unbindrule 'biao.score'-- 将biao表中的score列规则解除 exec sp_unbindrule 执行规则解除
--删除规则
drop rule g_guizhe; --吧g_guizhe规则彻底删除,删除时一定要保证和任何数据解除了关系否则删除不了
_____________________________________________
默认值设置
___________________________________________
--默认值创建
create default m_morengzhi as '男'-- 创建默认值为男 create default 创建默认的
--默认值绑定
use sample_db
go
exec sp_bindefault 'm_morengzhi','biao.sex'--吧规则绑定到sex数据中 sp_bindefault 默认值
--默认值解除
use sample_db
go
exec sp_unbindefault 'biao.sex'--删除绑定
--默认值删除
drop default m_morengzhi;--删除默认
_____________________________________________
主键
___________________________________________
create table j_jian
(
id int primary key,-- primary key创建主键
name varchar(25) not null,
deptId char(20) not null,
salary float not null,
);--一个或许需要的表
create table j_jian3
(
id int not null,
name varchar(25) not null,
deptId char(20) not null,
salary float not null,
constraint 员工编号 --constraint约束
primary key(id)-- primary key创建主键为id
);--第2个可能 需要的表
create table j_jian4
(
id int not null,-- primary key创建主键
name varchar(25) not null,
deptId char(20) not null,
salary float not null,
);--第3个或许需要的表
--没有id的时候代替id
create table j_jian5
(
name varchar(25),
deptId char(20) ,
salary float,
constraint 姓名部门约束 --constraint约束
primary key(name,deptid)-- primary key创建主键如果没有id用(name,deptid)来代替id
);--第4个可能 需要的表
create table j_jian6
(
id int primary key,
name varchar(25),
deptId int ,
salary float,
constraint kf_员工部门编号 foreign key(deptId) references j_jian(id)
);--第5个可能 需要的表
create table j_jian7
(
id int primary key,
name varchar(22)not null unique,--unique 指定姓名是唯一的
iocation varchar(50)
);
--第6个可能 需要的表
create table j_jian8
(
id int not null primary key,
name varchar(22)not null ,
iocation varchar(50)
constraint 部门名称 unique(name) --unique 后指定姓名是唯一的
);
--第7个可能 需要的表
create table j_jian9
(
id int primary key,
name varchar(22)not null ,
iocation varchar(50),
salary float not null
check(salary>1800 and salary<3000) --创建约束 必须在1800到3000里面
);
--第8个可能 需要的表
create table j_jian10
(
id int primary key,
name varchar(22)not null ,
iocation varchar(50),
salary float ,
deptId int default 1111 --指定一开始的默认值为1111 --默认值操作
);
--第9个可能 需要的表
--主键设置
use sample_db
go
alter table j_jian4 --在 j_jian4中命名主键
add
constraint 员工编号1--命名约束
primary key(id);--设置id为主键
--约束删除
alter table j_jian5
drop
constraint 姓名部门约束
--删除主键
alter table j_jing6
drop constraint 姓名部门约束
_____________________________________________
索引
___________________________________________
手动索引↑
代码索引
create unique clustered index s_suoying--创建唯一的聚集索引
on biao(id desc)--接通biao表的id desc 降序排列
with
fillfactor=30;
--查看索引信息
use sample_db
go
exec sp_helpindex 'biao'; --查看索引信息
--更换表名
use sample_db
go
exec sp_rename 'biao.multi_index3', 'multi_index4', 'index' --查看索引信息 第一个代表要更改的目标 第二个代表需要替换的值 第三个 代表目标的类型
--目标的类型有5种 COLUMN 代表列名 DATABASE 代表数据库 INDEX代表用户索引 OBJECT 代表 Check Foreign约束 USERDATATYPE代表 用户数据类型
--索引的删除
use sample_db
go
exec sp_helpindex 'biao'--删除前查看
drop index biao.s_suoying -- 删除biao表下的s_suoying索引
exec sp_helpindex 'biao'--删除后查看
_____________________________________________
事务
___________________________________________
use sample_db
declare @abc int
select @abc=(select count(*) from biao)--获取数据有几条
begin transaction --建立一个事务
insert into biao values (8,'张4','男','18',8,'null')
insert into biao values (9,'张4','男','18',9,'null')
if @abc>10
begin
rollback transaction --事务失败 不执行此事务
print '数据超过10条'
end
else
begin
commit transaction --事务成功提交事务
print '成功插入'
end
_____________________________________________
游标
___________________________________________
--定义游标
use sample_db“”
go
declare b_biao cursor for --声明一个为b_biao的游标 declare 声明 cursor for 游标
select name,sex from biao; --查看
--打开游标
use sample_db
go
open b_biao -- 打开游标 open 打开
--获取游标
use sample_db
go
fetch next from b_biao --获取下一个游标
while @@FETCH_STATUS=0 --循环输出游标 FETCH_STATUS 获取游标状态如果游标没有就停止
begin
fetch next from b_biao --获取下一个游标
end
--获取到的是当时选择查看的游标
--关闭游标
close b_biao --关闭游标
--释放游标
use sample_db
go
deallocate b_biao--释放游标
一套
use sample_db
go
declare @youbiao cursor
declare b_biao cursor for --声明游标变量
select sex,name from biao;--创建游标
open b_biao --打开游标
set @youbiao=b_biao --为游标变量赋值
fetch next from @youbiao --从游标中读取数据
while @@FETCH_STATUS=0 --判断FETCH语句是否执行成功
begin
fetch next from @youbiao --读取游标变量中的数据
end
close @youbiao --关闭游标
deallocate @youbiao --结束游标
--2套
use sample_db
go
declare b_biao cursor for --声明游标变量
select sex,name from biao--创建游标
where diyig=1
open b_biao --打开游标
fetch next from b_biao --从游标中读取数据
into @name,@sex
print '名字和性别分别为:'
print '名字:'+' 性别:'
while @@FETCH_STATUS=0 --判断FETCH语句是否执行成功
begin
print @f_name+' '+str(@f_sex,8,2)
fetch next from b_biao --读取游标变量中的数据
into @f_name,@f_sex
end
close @youbiao --关闭游标
deallocate @youbiao --结束游标
--系统存储管理
_____________________________________________
存储过程介绍
___________________________________________
_____________________________________________
存储过程操作
___________________________________________
use sample_db
go
create procedure c_ccgc –创建存储过程名称为c_ccgc
as – 吧里面的数当作一个函数用exec调用(下面有)
select *from fruits
go
use sample_db
go
create procedure c_ccgc2
as
select COUNT(*) as 总数 from fruits1 --count 计数
go
手动创建
--存储过程查看
use sample_db
go
exec c_ccgc --exec 执行存储过程里面写的东西
--查看
第2种查看: execute c_ccgc;--查看
如何修改函数
:
Sql删除存储过程
use sample_db
go
drop procedure dbo.c_ccgc;--删除存储过程
_____________________________________________
扩展存储过程
___________________________________________
exec xp_msver --返回系统信息
Index Name Internal_Value Character_Value
------ -------------------------------- -------------- ------------------------------------------------------------------
1 ProductName NULL Microsoft SQL Server
2 ProductVersion 720896 11.0.2218.0
3 Language 2052 中文(简体,中国)
4 Platform NULL NT x64
5 Comments NULL SQL
6 CompanyName NULL Microsoft Corporation
7 FileDescription NULL SQL Server Windows NT - 64 Bit
8 FileVersion NULL 2011.0110.2218.00 ((SQL11_RTM_GDR).120612-1251 )
9 InternalName NULL SQLSERVR
10 LegalCopyright NULL Microsoft Corp. All rights reserved.
11 LegalTrademarks NULL Microsoft SQL Server is a registered trademark of Microsoft Corporation.
12 OriginalFilename NULL SQLSERVR.EXE
13 PrivateBuild NULL NULL
14 SpecialBuild 145358848 NULL
15 WindowsVersion 602931718 6.2 (9200)
16 ProcessorCount 8 8
17 ProcessorActiveMask NULL ff
18 ProcessorType 8664 NULL
19 PhysicalMemory 16238 16238 (17027182592)
20 Product ID NULL NULL
----返回的信息
_____________________________________________
自定义函数的创建和使用方法
___________________________________________
自定义函数的创建
create function geststunanebyid(@c_zi int) --create function创建函数 geststunanebyid(@c_zi int) 传值,传入一个数值
returns varchar(30) --返回类型为字符类型
as
begin --开始
declare @chuangjing char(30) --声明数据
select @chuangjing=(select sex from age where diying=@c_zi)--需要查询的数据表名称
return @chuangjing --最终返回值
end --结束
自定义函数的创建(判断男女性别的创建)
create function c_chuangzhi(@c_zifu char(2)) --create function创建函数 geststunanebyid(@c_zi int) 传值,传入一个数值
returns table --table表格
as
return --返回的东西
(
select diyig,name,sex,age --需要返回的东西
from biao --返回的表名
where sex=@c_zifu -- 带条件返回 sex=@c_zifu条件为输入的东西
)
如何查询自定义的表值函数:
select *from c_chuangzhi('男') --里面是写的查找条件 查找性别为男的
_____________________________________________
数据库安全
___________________________________________
如何修改服务器生分认证登录设置
_____________________________________________
___________________________________________
1.select top 10 * from 成绩信息
作用:查询前十行数据 --倒序 输出 查询前10数据
2.select top 10 percent * from 成绩信息
作用:查询前10%行的数据
_____________________________________________
Sql sever 连接2张表输出2张表里面的东西
___________________________________________
sql 同时查询多个表 可以使用连表查询
比如
使用join
select s1.*,s2.* from s1 left join s2 on s1.id = s2.id;
利用where and
select s1.* ,s2.* from s1,s2 where s1.id = s2.id;
建议根据条件选择 第二条sql优于第一条
其次还可以 使用union
select * from A
union
select * from B
前提是A和B的字段数目录名称一样