SQL基础复习20120904
create database 数据库名 on (name='stu2' filename='c:\1.mdf' size=3mb filegrowth=3%)
log on (name='stu2_log' filename='c:\1.ldf' size=2mb maxsize=20mb filegrowth=2%)
创建表:
create table 表名(
a int primary key identity(1,1),
b nvarchar(10) unique,
c narchar(2) check (c in '男' or '女')
d int,
e int not null,
mail nvarchar(20) check (e like '%@%')
)
create table 表明(
sid int,
cid int,
name nvarchar(10),
primary key(sid),(cid),
foreign key(cid) references
)
drop table 表名
语句select insert update delete
1. select * from 表名 where 列名=值
2. select name
from 表1
inner join 表2
on 表1.id1=表2.id2
where 列名=值
group by name
having number > sum(number)
order by name desc / asc
3. select * from A where id in (
select id from B where name="值"
)
4. select * from (select 列1,列2,列3 from 表名) AA
5. inner join 表2 on 表1.id1=表2.id2
left join 表2 on 表1.id1=表2.id2
right join 表2 on 表1.id1=表2.id2
full join 表2 on 表1.id1=表2.id2
cross join 表2 on 表1.id1=表2.id2
insert语句
1. insert into A values (值1,值2,值3)
2. insert into B
select 值1,值2,值3 union
select 值1,值2,值3 union
select 值1,值2,值3
3. select into 表bu from 表cun --把表cun放到表bu中,表bu是不存在的表
4. insert into b
select * from a --把a插入到b中,b是存在的表
update语句
update 表名 set 列1=新值 where 列2=值
delete语句
delete from 表名 where 列1=值
delete a from a,b where 列1=值
索引
create unique clustered nonclustered
index 索引名
on a(表名,列名)
存储过程
create proc 存储过程名
declare @ii nchar(10) output,
declare @i int
as
语句
go
exec 存储过程名
declare @a int
declare @aa nchar(10) output
exec 存储过程名 @aa output ,@ a = 1
注意:output输出参数
触发器
create trigger t1
on 表名
for insert / update / delete
as
参数
语句
go
exec 触发器名
函数
表值函数(返回一个值)
标量函数(返回一个表)
create function f1 (int @a,int @b)
begin
return a
end
print dbo.函数名(3,4)
事务
begin transaction
rollback
commit
save transaction 名
rollback transaction 名
备份
sp_addumpdevice 'disk','stufull','c:\stufull.bak'
backup database 数据库名
to 备份名(stufull)
with init
sp_addumpdevice 'disk','stulog','c:\stulog.bak'
backup log 数据库名
to 备份名(stulog)
with init
还原数据库
restore datebase 数据库名 from 备份名 with replace
大致就这么多吧,有些还没记住!!
一些函数:
getdate
datediff(yy,'2000-9-9',getdate())
len(列名) 去字段长度
replace('2','3')
trim() 去掉空格
ltrim() 去掉左空格
rtrim() 去掉右空格
charindex('1','412ad34ggg56','5') 从第‘1’位置开始查找到第5个
right(‘12345年’,3) 从第四个位置右截取 5年
left('5年1safasdsd',2) 从第三个位置左截取 5年
datepart(mm,生日)=10 获取生日是10月份的
懒得输了
select convert(varchar(10),getdate(),120)