use Northwind
go
drop table backuptable
go
create table backuptable
(
-- Eid int identity(1,1),
Eid int,
Ename varchar (50) not null ,
--constraint pk_Eid primary key (Eid),
)
go
declare OrderCursor cursor --声明一个游标
for
select EmployeeID from Orders group by EmployeeID
go
declare @E_name varchar (50)
declare @OrdersCount int
declare @EmpID int
open OrderCursor--打开游标
fetch next from OrderCursor into @EmpID --先读到第一个记录
while(@@fetch_status=0)--判断是否读到了记录
begin
set @E_name=(select LastName+'-'+FirstName from Employees where EmployeeID=@empID)
set @OrdersCount=(select count(*) from Orders where EmployeeID=@empID)
insert into backuptable(Eid,Ename) values (@empID,@E_name)
fetch next from OrderCursor into @EmpID --读到下一个记录
end
close OrderCursor--关闭游标
DEALLOCATE OrderCursor--释放游标
范例
1、利用游标修改
declare UpdateCursor cursor --声明一个游标
for
select product_id from layer_product
go
declare @product_number varchar (50)
declare @product_id int
open UpdateCursor--打开游标
fetch next from UpdateCursor into @product_id --先读到第一个记录
while(@@fetch_status=0)--判断是否读到了记录
begin
set @product_number=(select product_number from product where
product_id=@product_id and delete_ind=0)
update layer_product set product_number=@product_number where
product_id=@product_id
fetch next from UpdateCursor into @product_id --读到下一个记录
end
close UpdateCursor--关闭游标
DEALLOCATE UpdateCursor--释放游标
2、利用游标插入
declare InsertCursor cursor --声明一个游标
for
select note_id from note where note_type='CO'
go
declare @note_id int
open InsertCursor--打开游标
fetch next from InsertCursor into @note_id --先读到第一个记录
while(@@fetch_status=0)--判断是否读到了记录
begin
insert into note_type_company(note_id,type_id,delete_ind) values(@note_id,1,0)
fetch next from InsertCursor into @note_id --读到下一个记录
end
close InsertCursor--关闭游标
DEALLOCATE InsertCursor--释放游标
eclare @IP varchar(50),@Email varchar(50)
declare tc cursor for select HostIP,UserEmail from RestartLog
open tc
fetch next from tc into @IP , @Email
while @@fetch_status = 0
begin
print @IP+' '+@Email
fetch next from tc into @IP , @Email
end
close tc
deallocate tc //删除对游标变量的引用
alter function fun_note_split_all(@split nvarchar(2))
returns @t table(master_id int,note_id int)
as
begin
declare InsertCursor cursor
for
select master_id,note_id from note where delete_ind=0
declare @master_id nvarchar(MAX),@note_id int
open InsertCursor--打开游标
fetch next from InsertCursor into @master_id,@note_id --先读到第一个记录
while(@@fetch_status=0)--判断是否读到了记录
begin
while(charindex(@split,@master_id) <> 0)
begin
insert @t(master_id,note_id) values (substring(@master_id,1,charindex(@split,@master_id)-1),@note_id)
set @master_id = stuff(@master_id,1,charindex(@split,@master_id), ' ')
end
insert @t(master_id,note_id) values (@master_id,@note_id)
fetch next from InsertCursor into @master_id,@note_id --读到下一个记录
end
close InsertCursor--关闭游标
DEALLOCATE InsertCursor--释放游标
return
end
select * from fun_note_split_all(',')