Pages

2013年8月16日 星期五

T-SQL 取代Cursor操作

轉仔自 : RICO技術農場 自己在工作開發上(雖然很少開發...XD)遇到要執行一筆一筆的操作,
我會盡量避免使用Cursor來處理(效能會很差),而想其他方法來取代,
剛好看到網友詢問,這裡順手紀錄針對一筆一筆操作不使用Cursor做法。

需求:取得來源資料表col2欄位並依col1條件逐筆更新目的資料表c2欄位(@desttbl)

  1. declare
  2. @step int,
  3. @uplimit int,
  4. @currentid int,
  5. @maxcount int,
  6. @nextrowid int,
  7. @c1data int,
  8. @c2data varchar(30);
  9. set @uplimit=1000;
  10. set @step=1;
  11. --建立來源資料表
  12. declare @sourcetbl table
  13. (
  14. col1 int identity(1,1) primary key not null,
  15. col2 varchar(30) null
  16. )
  17. --建立目的資料表
  18. declare @desttbl table
  19. (
  20. c1 int not null,
  21. c2 varchar(30) null,
  22. c3 datetime
  23. )
  24.  
  25. --新增資料
  26. while(@step<@uplimit+1)
  27. begin
  28. set @c1data=FLOOR((@uplimit)*RAND());
  29. insert into @sourcetbl values('rico'+convert(varchar,@step));
  30. insert into @desttbl values(@c1data,'',getdate());
  31. set @step=@step+1;
  32. end
  33. select @maxcount=count(1) from @sourcetbl;
  34. select @currentid=min(col1) from @sourcetbl;
  35. --取得來源資料表col2欄位並依col1條件更新目的資料表c2欄位(@desttbl)
  36. while(@currentid<=@maxcount)
  37. begin
  38. select
  39. @currentid=col1,
  40. @c2data=col2
  41. from @sourcetbl
  42. where col1=@currentid;
  43. update @desttbl set c2=@c2data where c1=@currentid;
  44.  
  45. -- 取得下一筆資料
  46. SELECT @nextrowid = MIN(col1)
  47. FROM @sourcetbl
  48. WHERE col1 > @currentid ;
  49. set @currentid=@nextrowid;
  50. end
  51. --查看結果
  52. select * from @desttbl
  53.  

Related Posts:

  • 鎖的問題 在SQL Server中使用加鎖的問題,我就以前的經驗和收集的一些資料簡單的提出我自己的一些看法,不知道對啟明星是否有所幫助: 一般而言,下面是個典型的打開資料庫的過程。 <% ’游標類型 Const adOpenForwardOnly = 0 Const adOpenKeyset = 1 Const adOpenDynamic =&nb… Read More
  • Microsoft JDBC 連接 URL 範例 在下列範例中,範例程式碼會在連接 URL 中設定各種連接屬性,然後呼叫 DriverManager 類別的 getConnection 方法,以傳回SQLServerConnection 物件。 接著,範例程式碼會使用 SQLServerConnection 物件的 createStatement 方法建立 SQLServerStatemen… Read More
  • SQL Server Studio Manager 抓取錯誤訊息直接利用 PRINT使用下列函式,即可印出錯誤訊息。 USE AdventureWorks2008R2; GO -- Verify that the stored procedure does not already exist. IF OBJECT_ID ( 'usp_GetErrorInfo', 'P' ) IS NOT NULL DROP PROCEDURE usp_GetErrorInfo; GO -- Create pro… Read More
  • T-SQL 取代Cursor操作轉仔自 : RICO技術農場 自己在工作開發上(雖然很少開發...XD)遇到要執行一筆一筆的操作, 我會盡量避免使用Cursor來處理(效能會很差),而想其他方法來取代, 剛好看到網友詢問,這裡順手紀錄針對一筆一筆操作不使用Cursor做法。 需求:取得來源資料表col2欄位並依col1條件逐筆更新目的資料表c2欄位(@desttbl) declare @step int, @uplimit int, @currentid int,… Read More
  • SQL中的GETDATE() 轉換函式與產生結果--Sql Server 中一个非常强大的日期格式化函数 Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AM Select CONVERT(varchar(100), GETDATE(), 1): 05/16/06 Select CONVERT(varchar(100), GETDATE(), 2): 06.05.16 Select CONVERT(varchar(100)… Read More

0 意見: