SQL语句大全

 (一)

(1)创建 / 删除数据库

1.创建之前判断该数据库是否存在

if exists (select * from sysdatabase where name = 'databaseName')

drop database databaseName    --若存在则删除

go   --新建

Create DATEBASE databasename 

 

drop database bdname    --删除后无法通过日志恢复

 

(2)创建 / 删除新表

create table tabname(col1 type1 [not null] [primary key].col2 type2[not null]...)

1.根据已有的表创建新表    ·

A:go

  use 原数据库名

  go

select * from 目的数据库名.dbo.目的表名 from 原表名(使用旧表创建新表)

B:create table tab_new as select col1,col2... from tab definition only

 

drop table tabname

 

(3)创建序列

create sequence SIMON_SEQUENCE

minvalue 1   --最小值

maxvalue 999999999999999999999999  --最大值

start with 1  --开始值

increment by 1   --每次加一

cache 20 

 

(4)增加 / 删除一个列

Alter table tabname add colname coltype

Alter table tabname drop column colname   --删除-列-列名

 

(5)添加 / 删除主键

Alter table tabname add primary key(col)

Alter table tabname drop primary key(col)

 

(6)增加 / 删除索引

create [unique] index idxname on tablename

drop index idxname on tabname

!!!索引不可更改,想要更改必须删掉重建

 

(7)创建 / 删除视图

create view viewname as select statename

drop view viewname

 

(8)创建备份数据的device

USE master

EXEC sp_addumpdevice 'disk','testBack','c:\mssql7backup\MyNwind_1.dat'

开始备份

BACKUP DATABASE puts TO testBase

 

(二)简单基本的SQL语句

(1)数据记录筛选

select * from 数据表 where 字段名=字段值 order by 字段名 [desc]    --按名查找

select * from 数据表 where 字段名 like '%字段值%' order by 字段名 [desc]  --按近似值查找

select top 10 * from 数据表 where 字段名=字段值 order by 字段名 [desc]  --取按名查找的前十个值

select top 10 * from 数据表 order by 字段名 [desc]   --取数据表中前十个值

select * from 数据表 where 字段名 in (值1,值2,值3)   --选出含某值的数据

select * from 数据表 where 字段名 between 值1 and 值2      --筛选某区间的值

(2)更新数据

updata 数据表 set 字段名=字段值 where 条件表达式   --条件满足时值被替换

updata 数据表 set 字段1=值1,字段2=值2.... where 条件表达式   --多个值被替换

(3)删除数据

delete from 数据表 where 条件表达式

delete from 数据表  --将数据表中所有记录删除,该记录表变成空表,表名仍存在

(4)添加数据

insert into 数据表 (字段1,字段2...) values (值1,值2...)

insert into 目标数据 select * from 源数据表   --把源数据表的记录添加到目标数据表

(5)数据记录统计函数

avg(字段名)  --求平均

count(*;字段名)   --行数统计

max(字段名) 

min(字段名)

sum(字段名)   --相加

select sum(字段名) as 别名 from 数据表 where 条件表达式

set rs = conn.excute(sql)  --用rs作为别名获取统计值

select distinct * from table1  --查询去除重复值

(5)数据表的建立和删除

create table 数据表名称(字段1 类型1(长度)...)

(6)单列求和

select sum (字段名) from 数据表

(三)几个高级查询运算词

(1)union

UNION 运算符通过组合其他两个结果表(例如TABLE1 和TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随UNION 一起使用时(即UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自TABLE1 就是来自TABLE2。

(2)except

EXCEPT 运算符通过包括所有在TABLE1 中但不在TABLE2 中的行并消除所有重复行而派生出一个结果表。当ALL 随EXCEPT 一起使用时(EXCEPT ALL),不消除重复行。

(3)intersect

INTERSECT 运算符通过只包括TABLE1 和TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当ALL 随INTERSECT 一起使用时(INTERSECT ALL),不消除重复行。

注:使用运算词的几个查询结果行必须是一致的。

posted @ 2018-05-21 22:17  库巴老爷  阅读(366)  评论(0编辑  收藏  举报