SQL SERVER 建临时表、循环插入数据、游标遍历数据库

来源:互联网 发布:网络不给力请点击刷新 编辑:程序博客网 时间:2024/06/06 05:19
  1. create table #tmp (id int)  --建立临时数据表  
  2.   
  3. declare @x int  --循环插入数据  
  4. set @x=1  
  5. while @x<=10  
  6. begin  
  7.     insert into #tmp values(@x)  
  8.     set @x=@x+1  
  9. end  
  10.   
  11. --建立游标 遍历数据库  
  12. declare tmpCursor CURSOR for    
  13. select * from #tmp  
  14. open tmpCursor  
  15.   
  16. declare @id int  
  17. fetch next from tmpCursor into @id  
  18.   
  19. while  @@FETCH_STATUS =0  
  20. begin  
  21.     print @id  
  22.     fetch next from tmpCursor into @id  
  23. end

  24. create procedure findName--创建一个名为findName的存储过程  
    AS
     declare @result VARCHAR(30)--用来处理结果的变量  
     begin  
     --声明一个游标  
      Declare curStudentFee Cursor for   
      SELECT NAME FROM SYSOBJECTS WHERE XTYPE='P';---查询语句(查询所有用户存储过程名称)  
         
       --打开游标  
      Open curStudentFee   
      --循环并提取记录  
      Fetch Next From curStudentFee Into @result--取第一条记录存入@result中  
      While ( @@Fetch_Status=0 )     
            begin  
            print ''''+@result+''''+',';---处理结果  
         Fetch Next From curStudentFee into @result----下一条  
           end   
      --关闭游标     
       Close curStudentFee
      --释放游标  
     Deallocate curStudentFee   
     end
     
原创粉丝点击