N.1 查询优化
1)索引优化
(1)创建索引
create unique index Index1 on dbo.newTbale3(SNO desc) -- 索引的这一列 必修没有重复值
with drop_existing --删除已存在的索引,创建新的索引
-- 索引的类型有三种 unique index、 clustered index、 nonclustered index
(2)删除索引
drop index newTbale3.Index1
(3)查看索引
sp_helpindex newTbale3
2)视图
(1)创建视图
create view stuView as select sno from Student;
select * from stuView;
(2)删除视图
drop view stuView
(3)查看视图
-- 下面直接运行就可以 是自带的
SELECT
Name,--视图名字
Definition --视图内容
FROM sys.sql_modules AS m INNER JOIN sys.all_objects AS o
ON m.object_id = o.object_id
WHERE o.[type] = 'v'
(4)判断视图是否存在
if Exists( SELECT * FROM dbo.sysobjects WHERE id = object_id('视图名') and xtype='V' ) print '存在'
else print '存在'
N.2 存储过程
和mysql不一样,没有存储函数的说法
1)基本的存储过程
(1)不带参数
[1] -- 创建过程
create procedure proc_find_stu5
as select * from test.dbo.table_1 where id =12
[2] -- 执行
exec proc_find_stu5 ;
(2)带输入参数
[1] -- 创建过程
create procedure proc_find_stu13(@id int = 1 ) -- 注意:传参数最好和匹配字段的数据类型一样,
不然.很可能查询不到任何结果 。注意尽量varchar 不要用char.测试发现 char会用空格补齐定义的固定长度
as select * from test.dbo.table_1 where id = @id
[2] -- 执行
exec proc_find_stu13 12;
(3)带输入和输出参数
[1] -- 带输入和输出参数
if (exists (select * from sys.objects where name = 'proc_find_stu16')) drop proc proc_find_stu16; -- 存在重复的存储过程 就删除掉
go -- 结束标志
create proc proc_find_stu16(@id int, @str varchar(50) out )
as select @str=str from test.dbo.table_1 where id = @id ;
[3] -- 执行
begin
declare @resStr varchar(50); -- 声明一个变量 用来保存 输出的值
exec proc_find_stu16 12,@resStr out; -- 注意 记得这里 加一个out
select @resStr as '返回结果';
end
2)带游标的存储过程
[1] 创建
if (exists (select * from sys.objects where name = 'myProc1')) drop proc myProc1; -- 存在重复存储过程就删除掉
go -- 结束符
CREATE PROCEDURE myProc1(@num int =0 ) AS
begin
declare @tmpData varchar(50);
declare cursor_tmp_1 cursor for select id from test.dbo.table_1 ; -- 保存集合
open cursor_tmp_1; -- 打开游标(集合)
fetch next from cursor_tmp_1 into @tmpData; --进行遍历指针移动
while @@fetch_status = 0 -- 如果上面获取到了数据,表@@fetch_status就会返回0. 0=0 就表示获取数据成功
begin
set @num=@num+1
-- 注意尽量varchar 不要用char.测试发现 char会用空格补齐定义的固定长度
print '输出第'+CAST(@num as varchar) + '次:' + @tmpData ;
-- 进行遍历指针移动,这个一定要写。不然就无法退循环 进入死循环
fetch next from cursor_tmp_1 into @tmpData;
end;
close cursor_tmp_1; -- 关闭游标
deallocate cursor_tmp_1; --释放游标.
end
[2] 执行
exec myProc1
/**
运行结果:
输出第1次:12
输出第2次:33
*/