sql使用cursor寫一個簡單的迴圈<轉>

taogchan發表於2012-08-30
 1。排錯
  和sql server較了一天的勁,只寫了兩個簡單的儲存過程。當然智商雖然不高還沒低到這個份上。大半天都是花費在排錯上了。
  System.Data.SqlClient.SqlException: SQL Server 不存在或訪問被拒絕。 at System.Data.SqlClient.ConnectionPool.GetConnection(Boolean& isInTransaction) at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction) at System.Data.SqlClient.SqlConnection.Open() at _20060409.WebForm1.test() in d:\work files\20060409\webform1.aspx.cs:line 52
  冷不丁報了這個錯,這個就是從程式裡連不上。在服務中除了MSSQLserverADHelper以外所有的服務都開啟了還是不行;名稱正確、無別名、沒起例項名稱;埠號伺服器端和客戶端都是1433。為了找出問題只好上網查查結果發現連上網線後這個毛病就沒了。暈,看來是少打了什麼補丁。
  2。寫迴圈
  首先需求是這樣的我手裡現在有兩張表,rights和roles。
  表結構如下:
  rights
  -------------------
  rightid int
  right varchar(20)
  
  ==========
  
  roles
  -------------------
  roleid int
  roletype int
  role varchar(20)
  rightid int
  
  在我的role表裡有一個角色admin。admin擁有right表中的所有許可權,但是有四個欄位,要是用手寫完我這個速度,加上這個數量我看也就算了。省了手上的力氣就要費腦子。
  在查詢分析器裡寫了半天,總算是吭哧出來了。
  首先使用truncate table把role原來的失敗資訊清掉,聽說會比delete快一點,只不過數量少看不出明顯效果。
  然後建立一個臨時的用於填充的儲存過程。
  create procedure TempFill
  
  declare mycursor cursor for
  select rightid from rights--這兩個是一句,定義遊標,然後從rights中取一個rightid給遊標
  
  open mycursor
  
  declare @rightid int--定義一個變數
  fetch mycursor into @rightid--把mycursor當前的值給@rightid
  
  while @@fetch_status=0
  begin
  insert into rolestable (roletype,role,rightid)values(1,'admin',@rightid)
  fetch mycursor into @rightid
  end
  
  close mycursor
  deallocate mycursor
  這樣就寫完了。
  execute TempFill 再執行他一下。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22392018/viewspace-742250/,如需轉載,請註明出處,否則將追究法律責任。

相關文章