Sql server的游標使用

2021-08-03 23:13:11 字數 783 閱讀 1163

專案需要為sql server的一張表,新增一列時間戳,為時間戳設定初始值,第一條資料取值乙個月前,往後的資料加1秒,使用游標完成。

先貼**:

create procedure modifydefault

as declare @j datetime;

declare @tmp varchar(72);

declare mycursor cursor for (select fd_id from prod_scm_account_info);

set @j=(dateadd(month,-1,getdate()));

open mycursor;

fetch next from mycursor into @tmp;

while @@fetch_status=0

begin

update prod_scm_account_info set fd_last_modified_time=@j where fd_id= @tmp;

set @j=dateadd(s,1,@j);

fetch next from mycursor into @tmp;

end ;

close mycursor;

deallocate mycursor;

goexec modifydefault

遇到兩個坑:1、使用declare定義變數時,一定要設定length,不然可能存在設定變數值不生效的問題。

2、使用where current of時,發現執行效率不是一般的低,後改為用id作游標。

SQL Server 游標使用

游標概念 資料庫操作中我們常常會遇到這樣情況,即從某一結果集中逐一地讀取一條記錄。那麼如何解決這種問題呢?游標為我們提供了一種極為優秀的解決方案。游標 cursor 是系統為使用者開設的乙個資料緩衝區,存放sql語句的執行結果。每個游標區都有乙個名字。使用者可以用sql語句逐一從游標中獲取記錄,並賦...

sqlserver游標使用

create procedure pk test as 宣告2個變數 declare o id nvarchar 20 declare a salary float 宣告乙個游標mycursor,select語句中引數的個數必須要和從游標取出的變數名相同 declare mycursor curso...

sqlserver游標使用

什麼是游標 結果集,結果集就是select查詢之後返回的所有行資料的集合。游標則是處理結果集的一種機制吧,它可以定位到結果集中的某一行,多資料進行讀寫,也可以移動游標定位到你所需要的行中進行運算元據。一般複雜的儲存過程,都會有游標的出現,他的用處主要有 定位到結果集中的某一行。對當前位置的資料進行讀...