游标等

--创建一个带参数的存储过程
create proc getempbyempname
@empname varchar(50)
as
select * from emp t
left join dept t2 on t.dept_id=t2.dept_id
where t.emp_name=@empname
go
exec getempbyempname '张三'
go


--执行带输入输出参数的存储过程
create proc twoemp_proc
@emp_id int,
@emp_name varchar(50) out
as
select @emp_name=emp_name from emp where emp_id=@emp_id
go
--执行存储过程
declare @emp_name varchar(50)
exec twoemp_proc @emp_id=1,@emp_name=@emp_name output
select @emp_name
drop proc twoemp_proc
go


--创建视图
create view three_view
as
select * from emp where emp.dept_id=1
go


--事务:开始事务、保存事务、回滚事务、提交事务
begin tran four_tran
update emp set emp_name='张三' where emp_name='马六';
save tran one
update emp set emp_name='李七' where emp_name='李四';
rollback tran one
commit tran four_tran
 

 go
--创建游标:声明、打开、使用、关闭、释放
--存储过程中使用游标
create proc proc_student
as
declare @counter int
declare @sid int
declare @sname varchar(20)
declare @sage datetime
declare @ssex varchar(2)
declare cursor_student cursor
scroll--此处用scroll来描述了游标,说明可以让游标的PRIOR和NEXT同时使用;可以让游标进行回滚
for
    select * from student --此处是给student加游标

    select @counter=1
open cursor_student
begin
    fetch next from cursor_student into @sid,@sname,@sage,@ssex
    print @sid
end

while @counter<=5 and @@FETCH_STATUS=0 --此while是循环下面的t-sql(begin end批处理里面的)
begin
    select @counter=@counter+1
    FETCH next from cursor_student into @sid,@sname,@sage,@ssex
    print @counter
end

while @counter>1 and @@FETCH_STATUS=0
    begin
        select @counter=@counter-1
        fetch prior from cursor_student into @sid,@sname,@sage,@ssex
        print @counter
    end
close cursor_student
deallocate cursor_student

exec proc_student
go



--事例
DECLARE Employee_Cursor CURSOR 
FOR  
    SELECT BusinessEntityID, JobTitle  
    FROM AdventureWorks2008.HumanResources.Employee;  
OPEN Employee_Cursor;  
    FETCH NEXT FROM Employee_Cursor;  
WHILE @@FETCH_STATUS = 0  
   BEGIN  
      FETCH NEXT FROM Employee_Cursor;  
   END;  
CLOSE Employee_Cursor;  
DEALLOCATE Employee_Cursor;  
GO

 

posted @ 2020-11-24 02:23  黄立明02  阅读(75)  评论(0编辑  收藏  举报