深入SQL Cursor基本用法的詳細介紹建站知識
導讀:1建站知識本篇文章是對SQL Cursor的基本用法進行了詳細的分析介紹,需要的朋友參考下seo網站關鍵詞優化公司網站建設。
由于這個游標 執行一下就相當于SELECT一下 其效率不敢恭維也沒做深入研究。
復制代碼 代碼如下:
table1結構如下 id int name varchar(50) declare @id int declare @name varchar(50) declare cursor1 cursor for --定義游標cursor1 select * from table1 --使用游標的對象(跟據需要填入select文) open cursor1 --打開游標 fetch next from cursor1 into @id,@name --將游標向下移1行,獲取的數據放入之前定義的變量@id,@name中 while @@fetch_status=0 --判斷是否成功獲取數據 begin update table1 set name=name+'1' where id=@id --進行相應處理(跟據需要填入SQL文) fetch next from cursor1 into @id,@name --將游標向下移1行 end close cursor1 --關閉游標 deallocate cursor1
游標一般格式:DECLARE 游標名稱 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...OPEN 游標名稱FETCH NEXT FROM 游標名稱 INTO 變量名1,變量名2,變量名3,...WHILE @@FETCH_STATUS=0 BEGIN SQL語句執行過程... ... FETCH NEXT FROM 游標名稱 INTO 變量名1,變量名2,變量名3,... ENDCLOSE 游標名稱DEALLOCATE 游標名稱 (刪除游標)復制代碼 代碼如下:
例子:/*功能:數據庫表格tbl_users數據deptid userid username1 100 a1 101 b2 102 c要求用一個sql語句輸出下面結果deptid username1 ab2 c[要求用游標實現設計: OK_008時間: 2006-05備注:無*/create table #Temp1(deptid int,企業網站建設userid int,username varchar(20)) --待測試的數據表create table #Temp2(deptid int,username varchar(20)) --結果表--先把一些待測試的數據插入到待測試表#Temp1中insert into #Temp1select 1,100,'a' union allselect 1,101,'b' union allselect 1,131,'d' union allselect 1,201,'f' union allselect 2,302,'c' union all select 2,202,'a' union allselect 2,221,'e' union allselect 3,102,'y' union all select 3,302,'e' union allselect 3,121,'t' --declare @deptid int,@username varchar(20)--定義游標declare Select_cursor cursor for select deptid,username from #Temp1open Select_cursorfetch next from Select_cursor into @deptid,@username --提取操作的列數據放到局部變量中while @@fetch_status=0 --返回被 FETCH 語句執行的最后游標的狀態/*@@FETCH_STATUS =0 FETCH 語句成功@@FETCH_STATUS =-1 FETCH 語句失敗或此行不在結果集中如何seo優化推廣網站@@FETCH_STATUS =-2 被提取的行不存在*/ begin --當表#Temp2列deptid存在相同的數據時,就直接在列username上追加@username值 if(exists(select * from #Temp2 where deptid=@deptid )) update #Temp2 set username=username +@username where deptid=@deptid else --插入新數據 ins公司網站建設ert into #Temp2 select @deptid,@username fetch next from Select_cursor into @deptid,@username endclose Select_cursor deallocate Select_cursorselect * from #Temp2 --測試結果Drop table #Temp1,#Temp2
聲明: 本文由我的SEOUC技術文章主頁發布于:2023-05-23 ,文章深入SQL Cursor基本用法的詳細介紹建站知識主要講述詳細介紹,深入,SQL網站建設源碼以及服務器配置搭建相關技術文章。轉載請保留鏈接: http://www.bifwcx.com/article/web_5919.html
- 上一篇:網站外鏈建設注意事項有哪些建站知識
- 下一篇:關鍵詞放在什么位置最好?建站知識