sql语法复习:增删查改,各种数据库对象创建和函数使用

推荐工具:机子配置较低的话,可以装Gsql这个工具获得sql执行环境(可作为手册查看内置数据类型 函数和存储过程等)

--之前数据库的东西接触不多,虽然基本的语法是了解,但不是很熟悉
--最近项目一直在折腾存储过程(一些数据逻辑都通过存储过程在数据库端实现),
--复习了一遍sql的东东,在此记录一下。

/*
--创建数据库
create database test
use test;
--创建表 字段定义列表 主键 外键
create table score (id int primary key, student varchar(30), subjectId int foreign key references subject(sid) ,score int );
*/

/*
--添加 删除 查询记录
insert into score (id,student,subject,score) values(1,'zhangsan','math', 73);
delete from score;
select * from score
*/

/*
--聚合函数 avg(), group by分组, order by 排序, having 对分组进行过滤
select student, avg(score) as avgscore from score group by student order by avgscore;
select student from score group by student having min(score)>80; --选出各科成绩都在80分以上的学生
*/

/*
--distinct 不重复的,关系运算符:(not) between ..and.., like '%si', in ('zhangsan','lisi')
select distinct student from score;
select * from score where score between 86 and 99;
select * from score where score not between 86 and 99;
select * from score where score = 93;
select * from score where score >86;
select * from score where score >=93;
select * from score where student like '%四';
select * from score where student in ('张三', '李四');
select * from score where not student in('张三', '李四'); -- where not field in (list)
*/

/*
-- and, or 逻辑运算符
select * from score where student='张三' and score >80;
select * from score where student = '张三' or student='李四'
*/

/*
--order by f1,f2 多字段排序
select * from score where student = '张三' or student='李四' order by score asc
select * from score where student='张三' or student='李四' order by score desc;

select * from score where student='张三' or student='李四' order by student, score;
*/

--插入 更新 删除
--insert into score values(7, '小段', '数学', 87);

--update score set score=60 where id=7;

--delete from score where score<70;

/*
--select top 2 选择前面若干条记录
select top 2 * from score;
select top 50 percent * from score;--前50%的记录
*/

/*
-- like模式匹配 通配符 % _ [] [^] [a-c]
select * from score where subject like '%文';
select * from score where subject not like '%文';
select * from score where subject like '_语';
select * from score where subject like '_[学,文]';
select * from score where subject like '_[^学,文]';
select * from customers where city like '[a-c]%';
*/


--select * from score;
--select * from stdinfo;

/*
-- as 给字段别名或表别名
select id as 'No.', student as '姓名', subject as '科目' ,score as '分数' from score;
select id as 'No.', student as [学生姓名] from score;
select s.student , s.subject, s.score from score as s;
*/

--inner join tbl2 on tbl1.scoreId=tbl2.scoreId 连接查询 扩展字段并筛选记录
--select score.student, score.subject, score.score, stdinfo.height from score inner join stdinfo on stdinfo.name = score.student;

/*
--插入新记录 全字段值列表 则不用列出字段
insert into stdinfo values(4,'小新',90,'cm');
select * from stdinfo;
*/

/*
--连接查询 inner join 内连,left join 左连接,right join 右连接
select score.student, score.subject, score.score, stdinfo.height from score inner join stdinfo on stdinfo.name = score.student;

select score.student, score.subject, score.score, stdinfo.height from score join stdinfo on stdinfo.name = score.student;
select score.student, score.subject, score.score, stdinfo.height from score left join stdinfo on stdinfo.name = score.student;
select score.student, score.subject, score.score, stdinfo.height from stdinfo left join score on stdinfo.name = score.student;
select score.student, score.subject, score.score, stdinfo.height from score right join stdinfo on stdinfo.name = score.student;
select score.student, score.subject, score.score, stdinfo.height from stdinfo right join score on stdinfo.name = score.student;
select score.student, score.subject, score.score, stdinfo.height from score full join stdinfo on stdinfo.name = score.student;
*/

/*
--union 结果集合并,要求两个结果集的字段数和字段类型相同
select id, student from score union select id, name from stdinfo;
select id, student from score union all select id, name from stdinfo;
*/

--create database test2;

/*
--查询结果集存入新表中
select * into score_back from score;
insert into score_back(student,score) select student,score from score;
*/

/*
--创建数据库和表
create database family;
use family;
create table person(id int, lname varchar(30), fname varchar(40), address varchar(200) ,city varchar(20) );
select * from person;
*/

/*
-->>sql constraint:
not null, unique, primary key,foreign key,check, default
*/

--getdate()函数 返回当前的日期时间
--select GETDATE() as Date

--create index 创建索引
--create index idx_s on score(student);

/*
--create view view_name as select * from tbl 创建视图
create view myinfo as select * from score
select * from sysobjects where xtype='v'
*/

/*
-- getdate(), datepart()
select GETDATE() as date;
select DATEPART(d, GETDATE() );
*/

/*
--聚合函数: avg(), count(),first(),max(),min(),sum()
select avg(score) as 'avgScore' from score;
select count(*) as rsAmount from score;
select count(subject) as subCount from score;
select count(distinct subject) as subDiffCount from score;
select first(score) from score;
select max(score) as maxScore from score;
select min(score) as minScore from score;
select sum(score) as sumScore from score;
*/

/*
--修改表结构 加字段
alter table score add py varchar(10);
update score set py='yuwen' where subject='语文';
*/

/*
--字符函数 len(),upper(),lower(),mid() 数学函数:round()
select len(py) as py from score;
select *, upper(py) as py from score;
update score set py = upper(py);
select getdate() as date;
update score set py=lower(py);
select mid(student,1,1) as fname from score;
select round(score,2) as score_pre from score;
*/


/*
--查看数据库表 和 表结构
use test
go
select * from sysobjects where xtype='u'
exec sp_help testTbl
select * from sys.databases
select @@version

*/
/*
--object_id()查找对象的id(从sysobjects表中), objectproperty(objId,prop)
select object_id('ptest')

select * from sysobjects

select * from sysobjects where id = object_id('ptest') and OBJECTPROPERTY(id, 'IsUserTable') = 1
*/

-------------------------------------------------------

/*
--查看当前数据库的用户
exec sp_helpuser
--查看数据库(内置数据库和用户创建的)
exec sp_helpdb
--查看当前数据库的表(包括:系统表、用户表和视图)
exec sp_tables
--查看表的明细(字段 约束..)
exec sp_help 'binaryTbl'
--查看存储过程定义
exec sp_helptext 'myproc'
--查看指定表的索引
exec sp_helpindex score
--设置数据库兼容级别
exec sp_dbcmptlevel 80
*/

--设置数据库的选项
--exec sp_dboption 'test', 'quoted identifier' ,'on'
--exec sp_dboption

--set quoted_identifier on
--use test

/*
-- test decimal(3,2)
create table ptest (f1 decimal(3,2)); --f1为1位整数部分,2位小数部分的数值
insert into ptest values(2.234545);
insert into ptest values(34.4454); --报错 会溢出
select * from ptest
*/

/*
-- test bit
drop table bitTbl;
create table bitTbl (f1 bit , f2 bit, f3 bit);
insert into bitTbl values(12,5,2); --非0为真 则转换成1
select * from bitTbl
*/

/*
-- test money
create table moneyTbl (f1 money, f2 smallmoney);
insert into moneyTbl values($234, $23.29);
select * from moneyTbl;
*/

/*
-- test binary, varbinary, image
create table binaryTbl (f1 binary, f2 varbinary(30), f3 image);
insert into binaryTbl values(0x123, 0xffff, 0x12fff02);
select * from binaryTbl;
--修改字段的数据类型
alter table binaryTbl alter column f2 varbinary(50);
alter table binaryTbl alter column f1 binary(40);
exec sp_help 'binaryTbl'
*/

--数据类型转换 cast(@var as datatype)
--select cast('2003-03-23 12:02:23.443'as smalldatetime) as smdt

/*
--变量的声明 赋值 和打印
declare @nvar nchar(26);
set @nvar = N'this is an unicode string';
print @nvar;
*/

/*
-- newid()函数 和 uniqueidentifier数据类型 convert(datatype, @var)函数
print newid()
declare @uid uniqueidentifier;
set @uid= newid();
print 'value of @uid is:' + convert(varchar(255), @uid);
*/

/*
--自定义数据类型的存储过程 sp_addtype
exec sp_addtype telephone , 'varchar(25)', 'not null'
exec sp_addtype fax, 'varchar(24)','not null';
exec sp_droptype fax
*/

/*
--变量的使用
declare @mycounter int;
set @mycounter = 18%5;
print convert(varchar(255), @mycounter);
*/

--id字段值都为'用户'
--select id='用户', student,score from score;

/*
--位运算符
declare @a int, @b int;
set @a = 5;
set @b = 10;
select @a & @b, @a | @b, @a^@b;
*/

/*
--变量用在where子句中
declare @score int, @py varchar(20);
set @score = 88;
select @py = 'shuxue';
select * from score where score>@score and py=@py;
*/

/*
--变量赋值 select
select * from dbo.score
declare @sc int;
select @sc = score from score;
print @sc;
*/

/*
--全局变量
print @@connections
print @@cpu_busy
print @@datefirst
print @@dbts
print @@identity
print @@langid
print @@language

print @@max_connections
print @@max_precision

print @@nestlevel
print @@options

print @@version
print @@spid
*/

/*
--while控制流 begin .. end
declare @i int, @r int;
set @i =0;
set @r = 0;
while @i<=100
begin
set @r = @i + @r;
set @i = @i + 1;
end
print @r
*/

/*
--语句标签 goto labelName
declare @i int, @r int
set @i = 0;
set @r = 0;
myloop:
set @r = @r + @i;
set @i = @i +1;
if @i<=100
goto myloop
print cast(@r as varchar(20));
*/

--use test
--go

--删除存储过程
--drop proc myproc

/*
--获取存储过程的返回值
declare @stud varchar(20), @rst int;
set @stud = '张三';
exec @rst = myproc @stud --获取存储过程的返回值
if @rst = 1
print 'very good'
else
print 'should come on'
go
*/

--查看存储过程定义
--exec sp_helptext 'myproc'

/*
--创建函数
create function cubicVolume(@len decimal(4,1), @width decimal(4,1), @h decimal(4,1))
returns decimal(12,3)
as
begin
return (@len * @width * @h)
end
go

print cast(dbo.cubicVolume(20,2,5) as varchar(20));
go
*/

/*
create function searchStud (@score int)
returns @studInfo table(id int,student varchar(30),subject varchar(20),score int,py varchar(10))
as
begin
insert @studInfo select * from score where score > @score
return
end
go

--drop function dbo.searchStud
select * from searchStud(88);
*/


/*
update dbo.score set score = 85 where id = 3;
select * from score;
*/

/*
-- case when 值转换
select student as '学生' , subject as '科目',
case
when score >80 then '优秀'
when score >70 then '良好'
else '不及格'
end as '成绩'
from score
go
*/

--sysindexes系统索引表
--select * from dbo.sysindexes;

/*
use test
go

if exists(select * from dbo.sysindexes where name='score_studIdx')
drop index score.score_studIdx
go

create nonclustered index score_studIdx on score(student)
go
*/

--exec sp_helpuser

/*
--查看指定表的索引,删除索引
exec sp_helpindex score
drop index score.score_studIdx
*/

你可能感兴趣的:(sql)