SQL SERVER 基础功法(内功增强)

--数据操作
select --从数据库表中检索数据行和列
insert --向数据库表添加新数据行
delete --从数据库表中删除数据行
update --更新数据库表中的数据

--数据定义
create table  --创建一个数据库表
drop table --从数据中删除一个表

alter table --修改数据库表结构

create view --创建一个视图
drop view --从数据中删除视图

create index --为数据库表创建一个索引
drop index --从数据库中删除索引

create procedure --创建一个存储过程
drop procedure --从数据库中删除存储过程

create trigger --创建一个触发器
drop trigger --从数据库中删除触发器

create schema --向数据库添加一个新模式
drop schema --从数据库中删除一个模式

create domain --创建一个数据值域
drop domain --从数据库中删除一个域
alter domain --改变域定义

--数据控制
grant --授予用户访问权限
deny --拒绝用户访问
revoke --解除用户访问权限

--程序化SQL
declare --为查询设定游标
explan --为查询描述访问计划
open --检索查询结果打开一个游标
fetch --检索一行查询结果
close --关闭游标
prepare --为动态执行准备SQL语句
execute --动态的执行SQL语句
describe --描述准备好的查询

--局部变量
--全局变量 (必须以@@开头)
declare @id char(10) --定义一个变量
set @id = '10010001' --为变量赋值
select @id = '10010001' --为变量赋值

-- if else 的使用
declare @x int @y int @z int
select @x = 1 @y = 2 @z = 3
if @x > @y
print 'x>y' --打印字符串
else if @y > @z
print 'y>z'
else
print 'z>y'

-- case
use pangu
update employee set e_wage = 
case when job_leve1 = '1' then e_wage*1.08
case when job_leve1 = '2' then e_wage*1.07
case when job_level = '3' then e_wage*1.06
else e_wage*1.05
end 

--while continue break
declare @x int @y int @c int
select @x = 1 @y = 1
while @y < 3
begin
    select @c = 100*@x+@y
	print @c --打印变量c的值
end
    select @x = @x+1
	select @y = 1
end 

--waitfor 例如: 等待1小时2分零3秒后 才执行select 语句
waitfor delay '01:02:03'
select * from employee
-- 例: 等到晚上23点零8分后才执行select语句
waitfor time '23:08:00'
select * from employee

-- 只能在使用like关键字的where子句中使用通配符
select * from table where s_name like '[a-zA-z]%'  --[]指定值的范围
select * from table where s_name like '[^F-M]' -- ^排除指定范围

select * from table order by s_name asc -- asc 升序
select * from table order by s_name desc --desc降序

-- 子查询
-- 除非能确保内层select只能返回一个行的值
-- 否则应在外层where子句中使用 in 限定符
s_name = (select s_name from table where id = 1)

-- distinct 去除重复的字段列
select distinct s_name from table

-- 左外部链接,t1中有的而t2中没有的以null表示
select * from t1,t2 where t1.id *= t2.id
select * from t1,t2 where t1.id =* t2.id -- 右外部链接
-- union 合并查询结果集,all 保存重复行
select s_name from t1 union [all] 

insert into table(s_name,s_number) value('xxx','xxx')
value(select s_name,s_number from table) --从select语句中查询值进行添加

update table set s_name = default -- 将s_name更改为默认值
truncate table -- 删除表中所有行,仍保持表的完整性
drop table -- 完全删除表

猜你喜欢

转载自newerdragon.iteye.com/blog/1666157
今日推荐