SQL 语法

  • 格式:docx
  • 大小:19.85 KB
  • 文档页数:3

SQL 语法(SQL Server数据库)
insert into [表名] [列名]values (值列表) <单行新增>
insert into [表名][列名] select (值列表) union <多行新增>(最后新增那条数据可省略union)
insert into [新表名] select [列名] from [源表名](将源表内的数据插入新表中) <备份>
insert [列名] into [表名] from [源表名](将源表数据插入新表中,新表可以不存在)<备份>
update [表名] set [列名]=[新列名] where [条件] <修改数据> delete from [表名] where [条件]
delete table [表名] where [条件]<删除表>
truncate table [表名] <删除表结构,标识列重置>
drop table [表名]<删除表结构>
Alter table tabname add column col type
alter table [表名] add [字段名] [约束]<增加字段>
alter table [表名]drop [字段名]
基础SQL语句:
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查
资料!
排序:select * from table1 order by field1,field2 升序和降序DESC ASC
总数:select count * as 取别名from table1
求和:select sum(field1) as 取别名from table1
平均:select avg(field1) as 取别名from table1
最大:select max(field1) as 取别名from table1
最小:select min(field1) as 取别名from table1
视图:
创建视图:create view 视图名as select statement
删除视图:drop view 视图名
修改视图:alter view 视图名as 查询语句
查询视图:use view 查询语句
索引:
创建索引:create [unique] index 索引名on [表名](列名)
删除索引:drop index 索引名
注:索引是不可更改的,想更改必须删除重新建。

主键:
添加主键:Alter table [表名] add primary key(col)
删除主键:Alter table [表名] drop primary key(col)
创建新表:
create table [新表名](col1 type1 [not null] [primary key],col2 type2 [not null],..)
根据已有的表创建新表:
A:create table tab_new like tab_old (使用旧表创建新表)
B:create table tab_new as select col1,col2… from tab_old definition only
sp_rename 改名:
更改当前数据库中用户创建对象(如表、列或用户定义数据类型)的名称。

语法
sp_rename [ @objname = ] 'object_name' ,
[ @newname = ] 'new_name'
[ , [ @objtype = ] 'object_type' ]
如:EXEC sp_rename 'newname','PartStock'
判断某一表PartStock中字段PartVelocity是否存在:
if exists (select * from syscolumns where id=object_id('PartStock') and name='PartVelocity')
print 'PartVelocity exists'
else print 'PartVelocity not exists'
另法:
判断表的存在性:
select count(*) from sysobjects where type='U' and name='你的表名'
判断字段的存在性:
select count(*) from syscolumns
where id = (select id from sysobjects where type='U' and name='你的表名') and name = '你要判断的字段名'
SQL嵌套语句:
简单嵌套。