您的位置:首页 > 数据库

SQL語句大全

2015-07-02 11:15 344 查看

--SQL 语句大全

--1. 创建数据库

create database database-name

--创建DB之前先查询DB是否存在,存在的话先删除在创建

if exists (select * from sysdatabase where name ='databasename')  drop database databasename go create database  databasename

--2. 删除数据库

drop database database-name

--3. 创建新表

create table table_name

(

  col1 int,

  col2 int not null,

  col3 nvarchar(10) not null  primary key,  --设置主Key

  col4 datetime not null default(getdate()),  ---获得系统时间

  col5 int  not null check(col5 >10 and col5 <20) , --添加约束 数值在10 到20之间

  col6 nvarchar(50)

)

--4. 删除表

drop table tablenaame

--5. 增加栏位

alert table tablename add column  colname colType  -- colType 指栏位的数据类型 例:int

--6. 增加主键

alert table tablename add  primary key(col)  alert table tablename  drop primary key(col)

--7. 创建视图

create view vieName as select  tablename

drop view viewName --删除视图

--8. 查询

select * from tablename where col1 like '%value1%'  --模糊查询

select * from tablename order by col1 desc  --排序 desc 降序,asc 升序排序

select COUNT(*) from tablename --总和(总共多少行) 

select SUM(colName) from tablename   --某个栏位求总和

select AVG(col1) from tablename

select MAX(col1) from tablename

select MIN(col1) from tablename

select top(10) * from tablename order by NEWID()   --NewID 为随机函数

select name from sysobjects where type='U'   ---列出数据库中所有表的表名

select name from syscolumns where id=object_id('tablename')  --列出数据库中表的栏位

select col1 from tablename1 intersect select col1 from tablename2  

--intersect 对两个SQL语句产生的结果做处理,作用有点像and的用法,所选择的值要存在于第一句和第二句的sql语句中才会被查询出来

select col1 from tablename1  minus select col1 from tablename2

--minus 对两个SQL语句产生的结果做处理,它先找出第一个SQL语句所产生的结果,然后看这些结果有没有在第二个sql语句的结果中,如果有的话就去除。还有一点就是如果第二个sql语句所产生的结果没有在第一个sql语句所产生的结果内,那么这个数据也去除。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: