我會盡量避免使用Cursor來處理(效能會很差),而想其他方法來取代,
剛好看到網友詢問,這裡順手紀錄針對一筆一筆操作不使用Cursor做法。
需求:取得來源資料表col2欄位並依col1條件逐筆更新目的資料表c2欄位(@desttbl)
- declare
- @step int,
- @uplimit int,
- @currentid int,
- @maxcount int,
- @nextrowid int,
- @c1data int,
- @c2data varchar(30);
- set @uplimit=1000;
- set @step=1;
- --建立來源資料表
- declare @sourcetbl table
- (
- col1 int identity(1,1) primary key not null,
- col2 varchar(30) null
- )
- --建立目的資料表
- declare @desttbl table
- (
- c1 int not null,
- c2 varchar(30) null,
- c3 datetime
- )
- --新增資料
- while(@step<@uplimit+1)
- begin
- set @c1data=FLOOR((@uplimit)*RAND());
- insert into @sourcetbl values('rico'+convert(varchar,@step));
- insert into @desttbl values(@c1data,'',getdate());
- set @step=@step+1;
- end
- select @maxcount=count(1) from @sourcetbl;
- select @currentid=min(col1) from @sourcetbl;
- --取得來源資料表col2欄位並依col1條件更新目的資料表c2欄位(@desttbl)
- while(@currentid<=@maxcount)
- begin
- select
- @currentid=col1,
- @c2data=col2
- from @sourcetbl
- where col1=@currentid;
- update @desttbl set c2=@c2data where c1=@currentid;
- -- 取得下一筆資料
- SELECT @nextrowid = MIN(col1)
- FROM @sourcetbl
- WHERE col1 > @currentid ;
- set @currentid=@nextrowid;
- end
- --查看結果
- select * from @desttbl
0 意見:
張貼留言