sql数据库随笔

数据库
修改表格  

如果SQL server 2008中无法修改表结构,提示错误为:不允许保存修改,……

解决方案:工具→选项→左侧的Designers→表设计器和数据库设计器

去掉“阻止保存要求重新创建表的更改”前面的钩,重新启动系统。

--修改数据库的名字将student的名字修改成xuesheng
sp_renamedb student,xuesheng

增加列:  

Alter table 表名 add 列名 列类型

--修改表,新加入列,注意与内置单词冲突的时候,列名加[]括起来
alter table xinxi add [int] varchar(10)
alter table xinxi add nianling int

删除列: 

alter table 表名 drop column 列名

--修改表删除一列
alter table xinxi drop column [int]

修改列的类型: 

alter table 表名 alter column 列名 新类型

Insert 增(添加) 

应用:表结构不变,只能增加一行或某个值在不是自增长的情况下才能赋值,列名用逗号隔开,值的次序默认为表的次序,如果输入的值不全,可在前面加需要输入的列名,顺序一一对应values值。

--插入数据
insert into xinxi values(1,'张三',96)
insert into xinxi values(2,'李四',91)
insert into xinxi values(3,'王五',69)

Delete 删除 

Delete from 表名       删除表内容(表结构还在)这种删除方式会写日志,所以自增长的序列号会往下延续,不断增加不会从头开始

Truncate table 表名          此删除将表清空,速度快,不写日志,故再输入从头开始

Delete from 表名 where 列名 关系表达式 值            多条件可以加and或or

列名between值1 and 值2 等同于列名<=值2 and 列名>=值1

列名 in(值1,值2,值3,...) 筛选出值为值1或值2或值3...的选项

表中选中某一数据值 按 ctrl+0 此值变为null

Update 改、更新 

Update 表名 set 列名=值,列名=值,…… where 列名 关系表达式 值

update xinxi set fenshu=100 where code=6

Retrieve 检索、查询 

select *fromselect 列名,列名,…… fromselect *fromwhere 列名 关系运算符 值 and 列名 关系运算符 值

select *fromwhere 列名 between 1 and 100  (范围查询)

select *from 列名 where 列名 in(3,4,5)

select distinct 列名 from 表    (列去重)

select *from 列名 where name like %5%       %任意多个任意字符;_一个任意字符

---查询语句,条件查询
select *from xinxi
select fenshu,name from xinxi
select fenshu,name from xinxi where name='李四'

select *from xinxi where fenshu between 80 and 100--范围
update xinxi set nianling = 26 where fenshu between 80 and 100
select distinct name from xinxi--针对一列去重显示

update xinxi set name='李四' where code = 9
select *from xinxi where name='李四' and nianling =26
select *from xinxi where name='李四' or nianling =26
select *from xinxi where name in ('李四','赵六')
select *from xinxi where name not in ('李四','赵六')
--模糊查询名字里面带四的,通配符%表示任意很多字符
select *from xinxi where name like '%四%'
--下划线表示任意一个字符
select *From xinxi where name like '李_'
--下划线加中括号,等同于in的功能,任意一组满足就查询出来
select *from xinxi where name like '_[李四,赵六,田七]'

筛选 

Select *from 表名 where 列名 关系表达式 值

去重 

Select distinct 列名 from 表名        去除这一列的重复值

模糊查询 

Select *from 表名 where 列名 like '王%'

通配符:%:任意多个字符;_:一个任意字符;[4,5,6]:中括号代表选里面的值其一

排序 

Select *from 表名 order by 列名 asc (升序) 或 desc (降序)

--按年龄排序,asc升序,desc降序,默认不写是升序
select *from xinxi order by nianling asc
select *from xinxi order by nianling desc
--按降序排列分数后,查前三名
select top 3 *from xinxi order by fenshu desc
--按条件查询后排序,查名字叫李四的人谁的分数最高
select top 1 *from xinxi where name='李四' order by fenshu desc
 
原文地址:https://www.cnblogs.com/w297613932/p/4222333.html